使用Aspose.Cells将文本转换为列
Contents
[
Hide
]
可能的使用场景
您可以使用 Microsoft Excel 将文本转换为列。此功能可从 数据 选项卡的 数据工具 下使用。为了将一列内容拆分为多个列,数据应该包含特定分隔符,例如逗号(或其他字符),根据此分隔符 Microsoft Excel 将单元格的内容拆分为多个单元格。Aspose.Cells 也通过 TextToColumns 方法提供了此功能。
使用Aspose.Cells将文本转换为列
以下示例代码说明了使用TextToColumns方法。 该代码首先将一些人名添加到第一个工作表的A列中。 名字由空格分隔为名和姓。 然后,在A列上应用TextToColumns方法,并将其保存为输出Excel文件。 如果您打开输出Excel文件,您将看到名字在A列中,姓在B列中,如此屏幕截图所示。
示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(ConvertTexttoCols.class) + "rows_cloumns/"; | |
//Create a workbook. | |
Workbook wb = new Workbook(); | |
//Access first worksheet. | |
Worksheet ws = wb.getWorksheets().get(0); | |
//Add people name in column A. Fast name and Last name are separated by space. | |
ws.getCells().get("A1").putValue("John Teal"); | |
ws.getCells().get("A2").putValue("Peter Graham"); | |
ws.getCells().get("A3").putValue("Brady Cortez"); | |
ws.getCells().get("A4").putValue("Mack Nick"); | |
ws.getCells().get("A5").putValue("Hsu Lee"); | |
//Create text load options with space as separator. | |
TxtLoadOptions opts = new TxtLoadOptions(); | |
opts.setSeparator(' '); | |
//Split the column A into two columns using TextToColumns() method. | |
//Now column A will have first name and column B will have second name. | |
ws.getCells().textToColumns(0, 0, 5, opts); | |
//Save the workbook in xlsx format. | |
wb.save(dataDir + "outputTextToColumns.xlsx"); |