Aspose.Cell保存工作表为文本或者CSV格式
Aspose.Cell是一款功能强大的Excel文件处理控件,在不需要安装第三方插件的情况下,对Excel文件进行读取,修改,删除,新增,转换等功能,支持几乎所有版本的Excel。在很多时候客户需要把工作表转换为文本格式,如TXT, TabDelim, CSV等,下面的代码阐述了如果保存完整的工作表为文本,您也可以通过修改下面的代码保存为CSV格式。
具体代码如下:
C#
string filePath = @"F:\Downloads\source.xlsx";
//Load your source workbook
Workbook workbook = new Workbook(filePath);
//0-byte array
byte[] workbookData = new byte[0];
//Text save options. You can use any type of separator
TxtSaveOptions opts = new TxtSaveOptions();
opts.Separator = '\t';
//Copy each worksheet data in text format inside workbook data array
for (int idx = 0; idx < workbook.Worksheets.Count; idx++)
{
//Save the active worksheet into text format
MemoryStream ms = new MemoryStream();
workbook.Worksheets.ActiveSheetIndex = idx;
workbook.Save(ms, opts);
//Save the worksheet data into sheet data array
ms.Position = 0;
byte[] sheetData = ms.ToArray();
//Combine this worksheet data into workbook data array
byte[] combinedArray = new byte[workbookData.Length + sheetData.Length];
Array.Copy(workbookData, 0, combinedArray, 0, workbookData.Length);
Array.Copy(sheetData, 0, combinedArray, workbookData.Length, sheetData.Length);
workbookData = combinedArray;
}
//Save entire workbook data into file
File.WriteAllBytes(filePath + ".out.txt", workbookData);
VB.NET
Dim filePath As String = "F:\Downloads\source.xlsx"
'Load your source workbook
Dim m_workbook As Workbook = New Workbook(filePath)
'0-byte array
Dim workbookData(0) As Byte
'Text save options. You can use any type of separator
Dim opts As TxtSaveOptions = New TxtSaveOptions()
opts.Separator = Chr(9)
'Copy each worksheet data in text format inside workbook data array
For idx As Integer = 0 To m_workbook.Worksheets.Count - 1
'Save the active worksheet into text format
Dim ms As MemoryStream = New MemoryStream()
m_workbook.Worksheets.ActiveSheetIndex = idx
m_workbook.Save(ms, opts)
'Save the worksheet data into sheet data array
ms.Position = 0
Dim sheetData() As Byte = ms.ToArray()
'Combine this worksheet data into workbook data array
Dim combinedArray() As Byte
ReDim combinedArray(workbookData.Length + sheetData.Length - 1)
Array.Copy(workbookData, 0, combinedArray, 0, workbookData.Length)
Array.Copy(sheetData, 0, combinedArray, workbookData.Length - 1, sheetData.Length)
workbookData = combinedArray
Next
'Save entire workbook data into file
File.WriteAllBytes(filePath + ".out.txt", workbookData)