This technical tip show how developers can covert entire workbook into text or CSV format. Sometime

This tip submitted by sherazam on 2013-07-24 02:23:04. It has been viewed 3957 times.
Rating of 5.3 with 34 votes



This technical tip show how developers can covert entire workbook into text or CSV format. Sometimes, you want to convert/save the entire workbook with multiple worksheets into text format. For text formats (e.g Txt, Tab Delimited, CSV etc), by default both Ms-Excel and Aspose.Cells save the contents of active worksheet only. The following code example explains how you can save your entire workbook into text format. We load the source workbook which could be any Ms-Excel or OpenOffice Spreadsheet (e.g xls, xlsx, xlsm, xlsb, ods etc) file and it could have any number of worksheets. After the execution of the code, it converts the data of all sheets inside the workbook into txt format. You can modify the same example to save your file into CSV format. By default TxtSaveOptions.Separator is comma, so you should not specify any separator if you want save your file in CSV format.
Sample Code for Saving Entire Workbook into Text or CSV Format.

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.setSeparator('\t');

//Copy each worksheet data in text format inside workbook data array
for (int idx = 0; idx < workbook.getWorksheets().getCount(); idx++)
{
//Save the active worksheet into text format
ByteArrayOutputStream bout = new ByteArrayOutputStream();
workbook.getWorksheets().setActiveSheetIndex(idx);
workbook.save(bout, opts);

//Save the worksheet data into sheet data array
byte[] sheetData = bout.toByteArray();

//Combine this worksheet data into workbook data array
byte[] combinedArray = new byte[workbookData.length + sheetData.length];
System.arraycopy(workbookData, 0, combinedArray, 0, workbookData.length);
System.arraycopy(sheetData, 0, combinedArray, workbookData.length, sheetData.length);

workbookData = combinedArray;
}

//Save entire workbook data into file
FileOutputStream fout = new FileOutputStream(filePath + ".out.txt");
fout.write(workbookData);
fout.close();





More tips

Help your fellow programmers! Add a tip!