使用Aspose.Cells将文本转换为列
Contents
[
Hide
]
可能的使用场景
你可以使用 Microsoft Excel 将文本转换为列。此功能在 Data Tools 下的 Data 选项卡中。为了将列内容拆分为多列,数据应包含特定分隔符,如逗号(或任何其他字符),Microsoft Excel 根据此字符将单元格内容拆分到多个单元格。Aspose.Cells 也提供此功能,使用 TextToColumns 方法。
使用Aspose.Cells将文本转换为列
以下示例代码说明了 TextToColumns 方法的用法。代码首先在第一个工作表的列A中添加一些人名,名字和姓氏用空格字符分隔。然后对A列应用 TextToColumns 方法,并将其保存为输出Excel文件。如果你打开 输出Excel文件,你会看到,名放在A列,姓放在B列,如截图所示。
示例代码
This file contains hidden or 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"); |