将Excel转换为CSV、TSV和Txt
将工作簿保存为文本或CSV格式
有时,您希望将包含多个工作表的工作簿转换或保存为文本格式。对于文本格式(例如TXT、TabDelim、CSV等),默认情况下,Microsoft Excel和Aspose.Cells都仅保存活动工作表的内容。
以下代码示例说明如何将整个工作簿保存为文本格式。加载源工作簿,可以是任何Microsoft Excel或OpenOffice电子表格文件(例如XLS、XLSX、XLSM、XLSB、ODS等),并且可以具有任意数量的工作表。
执行代码后,将会将工作簿中所有工作表的数据转换为TXT格式。
您可以修改相同的示例以将文件保存为CSV格式。默认情况下,TxtSaveOptions.Separator为逗号,因此在保存为CSV格式时不需要指定分隔符。
// 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); | |
// Load your source workbook | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
// Text save options. You can use any type of separator | |
TxtSaveOptions opts = new TxtSaveOptions(); | |
opts.Separator = '\t'; | |
opts.ExportAllSheets = true; | |
// Save entire workbook data into file | |
workbook.Save(dataDir + "out.txt", opts); |
使用自定义分隔符保存文本文件
文本文件包含无格式的电子表格数据。该文件是一种纯文本文件,可以在其数据之间具有一些自定义分隔符。
// 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); | |
string filePath = dataDir + "Book1.xlsx"; | |
// Create a Workbook object and opening the file from its path | |
Workbook wb = new Workbook(filePath); | |
// Instantiate Text File's Save Options | |
TxtSaveOptions options = new TxtSaveOptions(); | |
// Specify the separator | |
options.Separator = Convert.ToChar(";"); | |
// Save the file with the options | |
wb.Save(dataDir + "output.csv", options); | |