使用Aspose.Cells将文本转换为列
可能的使用场景
您可以使用Microsoft Excel将文本转换为列。此功能可从数据选项卡下的数据工具中获取。为了将一列的内容拆分为多个列,数据应包含特定的分隔符,例如逗号(或其他字符),Microsoft Excel根据其将单元格的内容拆分为多个单元格。Aspose.Cells还提供了通过Worksheet.Cells.TextToColumns()方法实现此功能。
使用Aspose.Cells将文本转换为列
以下示例代码解释了Worksheet.Cells.TextToColumns()方法的用法。代码首先在第一个工作表的列A中添加了一些人名。名和姓由空格字符分隔。然后,它在列A上应用Worksheet.Cells.TextToColumns()方法,并将其保存为输出excel文件。如果打开输出excel文件,您将会看到,名字在A列,姓氏在B列,如此屏幕截图所示。
示例代码
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
//Create a workbook. | |
Workbook wb = new Workbook(); | |
//Access first worksheet. | |
Worksheet ws = wb.Worksheets[0]; | |
//Add people name in column A. Fast name and Last name are separated by space. | |
ws.Cells["A1"].PutValue("John Teal"); | |
ws.Cells["A2"].PutValue("Peter Graham"); | |
ws.Cells["A3"].PutValue("Brady Cortez"); | |
ws.Cells["A4"].PutValue("Mack Nick"); | |
ws.Cells["A5"].PutValue("Hsu Lee"); | |
//Create text load options with space as separator. | |
TxtLoadOptions opts = new TxtLoadOptions(); | |
opts.Separator = ' '; | |
//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.Cells.TextToColumns(0, 0, 5, opts); | |
//Save the workbook in xlsx format. | |
wb.Save(dataDir + "outputTextToColumns.xlsx"); |