使用 Aspose.Cells 将文本转换为列
Contents
[
Hide
]
可能的使用场景
您可以使用 Microsoft Excel 将文本转换为列。此功能可从数据工具在下面数据标签。为了将一列的内容拆分为多列,数据应包含特定的分隔符,例如逗号(或任何其他字符),Microsoft Excel 将一个单元格的内容拆分为多个单元格。 Aspose.Cells 也通过以下方式提供此功能[文本到列](https://reference.aspose.com/cells/java/com.aspose.cells/cells#textToColumns(int,%20int,%20int,%20com.aspose.cells.TxtLoadOptions)) 方法。
使用 Aspose.Cells 将文本转换为列
下面的示例代码解释了[文本到列](https://reference.aspose.com/cells/java/com.aspose.cells/cells#textToColumns(int,%20int,%20int,%20com.aspose.cells.TxtLoadOptions)) 方法。该代码首先在第一个工作表的 A 列中添加一些人名。名字和姓氏由空格字符分隔。然后它应用[文本到列](https://reference.aspose.com/cells/java/com.aspose.cells/cells#textToColumns(int,%20int,%20int,%20com.aspose.cells.TxtLoadOptions) 方法,并将其保存为输出 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"); |