使用Aspose.Cells将文本转换为列

可能的使用场景

您可以使用Microsoft Excel将文本转换为列。此功能可在数据标签下的数据工具中找到。要将列的内容拆分为多个列,数据应包含特定的分隔符,例如逗号(或任何其他字符),基于该分隔符,Microsoft Excel将单元格的内容拆分为多个单元格。Aspose.Cells for Python via .NET 也通过 Worksheet.Cells.text_to_columns() 方法提供此功能。

使用 Aspose.Cells for Python Excel库进行文本列转换

以下示例代码解释了Worksheet.Cells.text_to_columns()方法的用法。代码首先在第一个工作表的列A中添加了一些人名。名和姓由空格字符分隔。然后,它在列A上应用Worksheet.Cells.text_to_columns()方法,并将其保存为输出excel文件。如果打开输出excel文件,您将会看到,名字在A列,姓氏在B列,如此屏幕截图所示。

todo:image_alt_text

示例代码

from aspose.cells import TxtLoadOptions, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# The path to the documents directory.
dataDir = RunExamples.GetDataDir(".")
# Create a workbook.
wb = Workbook()
# Access first worksheet.
ws = wb.worksheets[0]
# Add people name in column A. Fast name and Last name are separated by space.
ws.cells.get("A1").put_value("John Teal")
ws.cells.get("A2").put_value("Peter Graham")
ws.cells.get("A3").put_value("Brady Cortez")
ws.cells.get("A4").put_value("Mack Nick")
ws.cells.get("A5").put_value("Hsu Lee")
# Create text load options with space as separator.
opts = 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.text_to_columns(0, 0, 5, opts)
# Save the workbook in xlsx format.
wb.save(dataDir + "outputTextToColumns.xlsx")