Unable to recognize OLE stream - java

I want to read xml file and I use jxl. But I get error jxl.read.biff.BiffException: Unable to recognize OLE stream.
When I search the internet , Everbody say that You should save as Excel 97-2003 Workbook.But My excel file is Excel 97-2003 .How can I solve this ?
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class deneme {
private String inputFile;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
CellType type = cell.getType();
if (type == CellType.LABEL) {
System.out.println("I got a label "
+ cell.getContents());
}
if (type == CellType.NUMBER) {
System.out.println("I got a number "
+ cell.getContents());
}
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
deneme test = new deneme();
test.setInputFile("c:/data.xls");
test.read();
}
}

Just go and save again by clicking on Save As and choose Excel 97-2003 WorkBook.
it work for me....

Just renaming it to .xls file does not work.
You will have to manually go to Save as -> Excel 97-2003 Workbook and save it.

Related

java.lang.ArrayIndexOutOfBoundsException reading from excel file

I am trying to read the following data from an Excel sheet
With the following code
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public String readUsernameFromExcel() {
File src = new File("C:/filepath.xls");
try {
Workbook wb = Workbook.getWorkbook(src);
Sheet sh1 = wb.getSheet(0);
Cell a2 = sh1.getCell(0, 2);
data1 = a2.getContents().trim();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data1;
}
So when I try and get the cell 0,1 I can pick up the username 1000483 just fine. But when I try to read 0,2 and I get java.lang.ArrayIndexOutOfBoundsException: 2.
What I'm trying to do is read data from an excel sheet return it as a String and then pass it in to login my application. But it seems when I try 0,2 I'm going outside of what is expected. I've tried a few things such as a for loop
for (int rows = 0; rows < sh1.getRows(); rows++) {
Sheet sh1 = wb.getSheet(0);
Cell a2 = sh1.getCell(0, 2);
}
I understand the first number is the column and the second is the row. I also understand that the code isn't able to see past 0,1. I'm just at a loss as to how to get it to see the rest of the sheet after trying other solutions of the same problem.
sh1.getRows() returns 3. As loop starts from 0, sh1.getRows() needs to be decremented by 1 (as below). Below loop works fine and returns value properly.
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class Excel {
public static void main(String[] args) {
File src = new File("c:/filepath.xls");
try {
String data1;
Workbook wb = Workbook.getWorkbook(src);
Sheet sh1 = wb.getSheet(0);
for (int rows = 1; rows < sh1.getRows(); rows++) {
for (int column = 0; column <= sh1.getColumns()-1; column++) {
Cell a2 = sh1.getCell(column, rows);
data1 = a2.getContents().trim();
System.out.println(data1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above code works and fetches the date without error
I use the same data with you, and I could get 1000484 value through my code.
Here is my code :
package com.jason.xls;
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class XlsParser {
public static void main(String[] args) {
final String path = "/home/coder/filepath.xls";
System.out.println(readUserNameFromXls(path));
}
public static String readUserNameFromXls(final String path) {
File file = new File(path);
try {
Workbook wb = Workbook.getWorkbook(file);
Sheet sheet = wb.getSheet(0);
Cell a2 = sheet.getCell(0, 2);
return a2.getContents().trim();
} catch (Exception e) {
return null;
}
}
}
I download jxl.jar from jxl.jar download here
My code result is : Code Result Image

extracting contents from csv using java

I need a java program that would extract info from a .csv file and run commands on a sql bank.
I've made a program that is working great so far, but I've made it to work with .xsl by mistake and can't make it to work with a csv file
here is the code:
package teste3;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class Teste3 {
private String inputFile;
String[][] data = null;
String[][] user = null;
public void setInputFile(String inputFile)
{
this.inputFile = inputFile;
}
public String[][] read() throws IOException
{
File inputWorkbook = new File(inputFile);
Workbook w;
try
{
w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
data = new String[sheet.getColumns()][sheet.getRows()];
user = new String[sheet.getColumns()][sheet.getRows()];
int j = 11;
int a = 0;
sheet.getColumns();
{
for (int i = 1; i < sheet.getRows(); i++)
{
Cell cell = sheet.getCell(j, i);
data[0][i] = cell.getContents();
System.out.println(cell.getContents());
}
}
j= 9;
for (int i = 1; i < sheet.getRows(); i++)
{
Cell cell = sheet.getCell(j, i);
user[0][i] = cell.getContents();
System.out.println(user[0] [i]);
}
}
catch (BiffException e)
{
}
return data;
}
public static void main(String[] args) throws IOException
{
Teste3 test = new Teste3();
test.setInputFile("C:\\Users\\a0046059\\Documents\\teste.xls");
test.read();
}
}
the program is really simple because of my lack of skills.
Can anyone help me ?
Thank you.

Error in opening an mail attached excel file created using Apache POI

I am creating an excel sheet using Apache POI and then sending the same file using Java GWT.The file created is all right.Now in the mail there are two options- Save or open.When I save the file in machine it is working fine but when I try to open ,it opens in notepad.In the suggestion too it is not showing excel. Here is my code to create the excel sheet:
package com.ericsson.egi.sxs.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import com.ericsson.egi.sxs.persistence.entity.AssetOrder;
public class CreateExcelFile {
int rownum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
CreateExcelFile() {
}
public File createWeeklyReport(List<AssetOrder> tempOrderList) throws Exception {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
List<String> headerRow = new ArrayList<String>();
headerRow.add("Name of Supplier/Vendor");
headerRow.add("Description of Contract");
headerRow.add("Initiator");
headerRow.add("Type Of Contract");
headerRow.add("Template Source");
headerRow.add("Savings");
headerRow.add("Payment Term");
headerRow.add("Code of Conduct Signed by Supplier");
headerRow.add("RoHS clause Included");
headerRow.add("Agreement No");
headerRow.add("Agreement Validity From ");
headerRow.add("Agreement Validity To");
headerRow.add("Sanctioned Parties List Screening");
headerRow.add("Sanctioned Parties List Screening Reasons in case no answer NO");
headerRow.add("Registered in CLM");
headerRow.add("Registered in CLM reasons if answer NO");
headerRow.add("Current State");
headerRow.add("Next State");
headerRow.add("TAT for L1");
headerRow.add("TAT for L2");
headerRow.add("TAT for L3");
headerRow.add("TAT for L4");
headerRow.add("Current State Comments");
List<List> recordToAdd = new ArrayList<List>();
recordToAdd.add(headerRow);
for (AssetOrder order : tempOrderList ) {
List<String> row = new ArrayList<String>();
row.add(order.getSourcingDetails().getVendorName());
row.add(order.getSourcingDetails().getContractDescription());
row.add(order.getSourcingDetails().getInitiatorName());
row.add(order.getSourcingDetails().getContractType());
row.add(order.getSourcingDetails().getTemplateSource());
row.add(order.getSourcingDetails().getSavings());
row.add(order.getSourcingDetails().getPaymentTerm());
if (order.getSourcingDetails().getIsCOCSigned()) {
row.add("YES");
} else {
row.add("NO");
}
if (order.getSourcingDetails().getIsROHSIncluded()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getAgreementNo());
row.add(order.getSourcingDetails().getValidityFrom().toString());
row.add(order.getSourcingDetails().getValidityTo().toString());
if (order.getSourcingDetails().getIsSPLScreening()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForSPL());
if (order.getSourcingDetails().getIsRegisteredInCLM()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForCLM());
row.add(order.getStatusMaster().getStatusName());
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(order.getComments());
recordToAdd.add(row);
}
CreateExcelFile cls = new CreateExcelFile(recordToAdd);
File file = cls.createExcelFile(tempOrderList.get(0).getOrderRequesterSignum());
return file;
}
File createExcelFile(String requesterSignum) {
FileOutputStream fos = null;
File file = new File("/tmp/" + requesterSignum + "_StatusReport.xls");
try {
fos=new FileOutputStream(file);
HSSFCellStyle hsfstyle=workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short)245);
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
CreateExcelFile(List<List> l1) throws Exception {
try {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2= l1.get(j);
for(int k=0; k<l2.size(); k++)
{
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Try with other Excel Extension as per your Excel version installed on your machine.
--EDIT--
May be the issue is related to Content Type. Please confirm what are you using for this?
response.setContentType("APPLICATION/OCTET-STREAM");
// try this one if above doesn't work
//response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");

how to retrive the values for dropdown list and checkboxes from excel and use those values in selenium webdriver

I am new to selenium webdriver. I am trying to retrieve the values from excel sheet for dropdownlist and checkboxes/radio button and use those values in selenium webdriver. Can you please give some suggestions for how to retrieve those values?
Thanks in advance.
//download jxl.jar and put it in your build path
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
//******************************************************************************************
public String setWorkbook(Workbook workbook) {
String sFullPathNameExcelFile = getXmlConfig().getString("data.input_excel");
// hard coded:
// String sFullPathNameExcelFile = "C:\\user\\MyExcel.xls";
try {
this.workbook = Workbook.getWorkbook(new File(
sFullPathNameExcelFile));
} catch (Exception ex) {
System.out.println("******* ERROR *******\n******* ERROR *******\n******* ERROR *******");
System.out.println(sFullPathNameExcelFile+" DOES NOT EXIST OR CANNOT BE OPENED FOR INPUT.");
System.out.println("******* ERROR *******\n******* ERROR *******\n******* ERROR *******");
System.exit(0);
}
return sFullPathNameExcelFile;
}// end method
//*****************************************************************************
public String setSheet(Sheet sheet) {
String sWorksheet = getXmlConfig().getString(
"data.worksheet");
try{
this.sheet = workbook.getSheet(sWorksheet);}
catch (Exception ex) {return "ERROR";}
return sWorksheet;
}
//******************************************************************************
public Sheet getSheet() {
return sheet;
}
public static void main(String[] args) throws Exception {
Workbook workbook = null;
pca.sWorkingExcelFile = pca.setWorkbook(workbook);
int iCol = 27; //whatever you need
int iRow = 34; //whatever you need
Cell cCell = null;
Sheet sheet = pca.getSheet();
cCell = sheet.getCell(iCol,iRow);
String str = cCell.getContents();
}

Writing a large resultset to an Excel file using POI

This is sort of inline w/ Writing a large ResultSet to a File but the file in question is an Excel file.
I'm using the Apache POI library to write an Excel file with a large data set retrieved from a ResultSet object. The data could range from a few thousand records to about 1 million; not sure how this translates into file system bytes in Excel format.
The following is a test code I wrote to check out the time taken to write such a large result set and also the performance implication w.r.t CPU & Memory.
protected void writeResultsetToExcelFile(ResultSet rs, int numSheets, String fileNameAndPath) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileNameAndPath));
int numColumns = rs.getMetaData().getColumnCount();
Workbook wb = ExcelFileUtil.createExcelWorkBook(true, numSheets);
Row heading = wb.getSheetAt(0).createRow(1);
ResultSetMetaData rsmd = rs.getMetaData();
for(int x = 0; x < numColumns; x++) {
Cell cell = heading.createCell(x+1);
cell.setCellValue(rsmd.getColumnLabel(x+1));
}
int rowNumber = 2;
int sheetNumber = 0;
while(rs.next()) {
if(rowNumber == 65001) {
log("Sheet " + sheetNumber + "written; moving onto to sheet " + (sheetNumber + 1));
sheetNumber++;
rowNumber = 2;
}
Row row = wb.getSheetAt(sheetNumber).createRow(rowNumber);
for(int y = 0; y < numColumns; y++) {
row.createCell(y+1).setCellValue(rs.getString(y+1));
wb.write(bos);
}
rowNumber++;
}
//wb.write(bos);
bos.close();
}
Not much luck with the above code. The file which is created seems to grow rapidly (~70Mb per sec). So I stopped the execution after about 10 minutes (killed the JVM when the file reaches 7Gb) and tried to open the file in Excel 2007. The moment I open it, the file size becomes 8k(!) and only the header and the first row are created. Not sure what I'm missing here.
Any ideas?
Using SXSSF poi 3.8
package example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SXSSFexample {
public static void main(String[] args) throws Throwable {
FileInputStream inputStream = new FileInputStream("mytemplate.xlsx");
XSSFWorkbook wb_template = new XSSFWorkbook(inputStream);
inputStream.close();
SXSSFWorkbook wb = new SXSSFWorkbook(wb_template);
wb.setCompressTempFiles(true);
SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk
for(int rownum = 4; rownum < 100000; rownum++){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < 10; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
}
}
FileOutputStream out = new FileOutputStream("tempsxssf.xlsx");
wb.write(out);
out.close();
}
}
It requires:
poi-ooxml-3.8.jar,
poi-3.8.jar,
poi-ooxml-schemas-3.8.jar,
stax-api-1.0.1.jar,
xml-apis-1.0.b2.jar,
xmlbeans-2.3.0.jar,
commons-codec-1.5.jar,
dom4j-1.6.1.jar
Useful link
Oh. I think you're writing the workbook out 944,000 times. Your wb.write(bos) call is in the inner loop. I'm not sure this is quite consistent with the semantics of the Workbook class? From what I can tell in the Javadocs of that class, that method writes out the entire workbook to the output stream specified. And it's gonna write out every row you've added so far once for every row as the thing grows.
This explains why you're seeing exactly 1 row, too. The first workbook (with one row) to be written out to the file is all that is being displayed - and then 7GB of junk thereafter.
Unless you have to write formulas or formatting you should consider writing out a .csv file. Infinitely simpler, infinitely faster, and Excel will do the conversion to .xls or .xlsx automatically and correctly by definition.
You can using SXSSFWorkbook implementation of Workbook, if you use style in your excel ,You can caching style by Flyweight Pattern to improve your performance.
You can increase the performance of excel export by following these steps:
1) When you fetch data from database, avoid casting the result set to the list of entity classes. Instead assign it directly to List
List<Object[]> resultList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
instead of
List<Employee> employeeList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
2) Create excel workbook object using SXSSFWorkbook instead of XSSFWorkbook and create new row using SXSSFRow when the data is not empty.
3) Use java.util.Iterator to iterate the data list.
Iterator itr = resultList.iterator();
4) Write data into excel using column++.
int rowCount = 0;
int column = 0;
while(itr.hasNext()){
SXSSFRow row = xssfSheet.createRow(rowCount++);
Object[] object = (Object[]) itr.next();
//column 1
row.setCellValue(object[column++]); // write logic to create cell with required style in setCellValue method
//column 2
row.setCellValue(object[column++]);
itr.remove();
}
5) While iterating the list, write the data into excel sheet and remove the row from list using remove method. This is to avoid holding unwanted data from the list and clear the java heap size.
itr.remove();
For now I took #Gian's advice & limited the number of records per Workbook to 500k and rolled over the rest to the next Workbook. Seems to be working decent. For the above configuration, it took me about 10 mins per workbook.
I updated BigGridDemo to support multiple sheets.
BigExcelWriterImpl.java
package com.gdais.common.apache.poi.bigexcelwriter;
import static com.google.common.base.Preconditions.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
public class BigExcelWriterImpl implements BigExcelWriter {
private static final String XML_ENCODING = "UTF-8";
#Nonnull
private final File outputFile;
#Nullable
private final File tempFileOutputDir;
#Nullable
private File templateFile = null;
#Nullable
private XSSFWorkbook workbook = null;
#Nonnull
private LinkedHashMap<String, XSSFSheet> addedSheets = new LinkedHashMap<String, XSSFSheet>();
#Nonnull
private Map<XSSFSheet, File> sheetTempFiles = new HashMap<XSSFSheet, File>();
BigExcelWriterImpl(#Nonnull File outputFile) {
this.outputFile = outputFile;
this.tempFileOutputDir = outputFile.getParentFile();
}
#Override
public BigExcelWriter createWorkbook() {
workbook = new XSSFWorkbook();
return this;
}
#Override
public BigExcelWriter addSheets(String... sheetNames) {
checkState(workbook != null, "workbook must be created before adding sheets");
for (String sheetName : sheetNames) {
XSSFSheet sheet = workbook.createSheet(sheetName);
addedSheets.put(sheetName, sheet);
}
return this;
}
#Override
public BigExcelWriter writeWorkbookTemplate() throws IOException {
checkState(workbook != null, "workbook must be created before writing template");
checkState(templateFile == null, "template file already written");
templateFile = File.createTempFile(FilenameUtils.removeExtension(outputFile.getName())
+ "-template", ".xlsx", tempFileOutputDir);
System.out.println(templateFile);
FileOutputStream os = new FileOutputStream(templateFile);
workbook.write(os);
os.close();
return this;
}
#Override
public SpreadsheetWriter createSpreadsheetWriter(String sheetName) throws IOException {
if (!addedSheets.containsKey(sheetName)) {
addSheets(sheetName);
}
return createSpreadsheetWriter(addedSheets.get(sheetName));
}
#Override
public SpreadsheetWriter createSpreadsheetWriter(XSSFSheet sheet) throws IOException {
checkState(!sheetTempFiles.containsKey(sheet), "writer already created for this sheet");
File tempSheetFile = File.createTempFile(
FilenameUtils.removeExtension(outputFile.getName())
+ "-sheet" + sheet.getSheetName(), ".xml", tempFileOutputDir);
Writer out = null;
try {
out = new OutputStreamWriter(new FileOutputStream(tempSheetFile), XML_ENCODING);
SpreadsheetWriter sw = new SpreadsheetWriterImpl(out);
sheetTempFiles.put(sheet, tempSheetFile);
return sw;
} catch (RuntimeException e) {
if (out != null) {
out.close();
}
throw e;
}
}
private static Function<XSSFSheet, String> getSheetName = new Function<XSSFSheet, String>() {
#Override
public String apply(XSSFSheet sheet) {
return sheet.getPackagePart().getPartName().getName().substring(1);
}
};
#Override
public File completeWorkbook() throws IOException {
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
ZipOutputStream zos = new ZipOutputStream(out);
Iterable<String> sheetEntries = Iterables.transform(sheetTempFiles.keySet(),
getSheetName);
System.out.println("Sheet Entries: " + sheetEntries);
copyTemplateMinusEntries(templateFile, zos, sheetEntries);
for (Map.Entry<XSSFSheet, File> entry : sheetTempFiles.entrySet()) {
XSSFSheet sheet = entry.getKey();
substituteSheet(entry.getValue(), getSheetName.apply(sheet), zos);
}
zos.close();
out.close();
return outputFile;
} finally {
if (out != null) {
out.close();
}
}
}
private static void copyTemplateMinusEntries(File templateFile,
ZipOutputStream zos, Iterable<String> entries) throws IOException {
ZipFile templateZip = new ZipFile(templateFile);
#SuppressWarnings("unchecked")
Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) templateZip.entries();
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
if (!Iterables.contains(entries, ze.getName())) {
System.out.println("Adding template entry: " + ze.getName());
zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = templateZip.getInputStream(ze);
copyStream(is, zos);
is.close();
}
}
}
private static void substituteSheet(File tmpfile, String entry,
ZipOutputStream zos)
throws IOException {
System.out.println("Adding sheet entry: " + entry);
zos.putNextEntry(new ZipEntry(entry));
InputStream is = new FileInputStream(tmpfile);
copyStream(is, zos);
is.close();
}
private static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] chunk = new byte[1024];
int count;
while ((count = in.read(chunk)) >= 0) {
out.write(chunk, 0, count);
}
}
#Override
public Workbook getWorkbook() {
return workbook;
}
#Override
public ImmutableList<XSSFSheet> getSheets() {
return ImmutableList.copyOf(addedSheets.values());
}
}
SpreadsheetWriterImpl.java
package com.gdais.common.apache.poi.bigexcelwriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Calendar;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.util.CellReference;
class SpreadsheetWriterImpl implements SpreadsheetWriter {
private static final String XML_ENCODING = "UTF-8";
private final Writer _out;
private int _rownum;
SpreadsheetWriterImpl(Writer out) {
_out = out;
}
#Override
public SpreadsheetWriter closeFile() throws IOException {
_out.close();
return this;
}
#Override
public SpreadsheetWriter beginSheet() throws IOException {
_out.write("<?xml version=\"1.0\" encoding=\""
+ XML_ENCODING
+ "\"?>"
+
"<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
_out.write("<sheetData>\n");
return this;
}
#Override
public SpreadsheetWriter endSheet() throws IOException {
_out.write("</sheetData>");
_out.write("</worksheet>");
closeFile();
return this;
}
/**
* Insert a new row
*
* #param rownum
* 0-based row number
*/
#Override
public SpreadsheetWriter insertRow(int rownum) throws IOException {
_out.write("<row r=\"" + (rownum + 1) + "\">\n");
this._rownum = rownum;
return this;
}
/**
* Insert row end marker
*/
#Override
public SpreadsheetWriter endRow() throws IOException {
_out.write("</row>\n");
return this;
}
#Override
public SpreadsheetWriter createCell(int columnIndex, String value, int styleIndex)
throws IOException {
String ref = new CellReference(_rownum, columnIndex).formatAsString();
_out.write("<c r=\"" + ref + "\" t=\"inlineStr\"");
if (styleIndex != -1) {
_out.write(" s=\"" + styleIndex + "\"");
}
_out.write(">");
_out.write("<is><t>" + value + "</t></is>");
_out.write("</c>");
return this;
}
#Override
public SpreadsheetWriter createCell(int columnIndex, String value) throws IOException {
createCell(columnIndex, value, -1);
return this;
}
#Override
public SpreadsheetWriter createCell(int columnIndex, double value, int styleIndex)
throws IOException {
String ref = new CellReference(_rownum, columnIndex).formatAsString();
_out.write("<c r=\"" + ref + "\" t=\"n\"");
if (styleIndex != -1) {
_out.write(" s=\"" + styleIndex + "\"");
}
_out.write(">");
_out.write("<v>" + value + "</v>");
_out.write("</c>");
return this;
}
#Override
public SpreadsheetWriter createCell(int columnIndex, double value) throws IOException {
createCell(columnIndex, value, -1);
return this;
}
#Override
public SpreadsheetWriter createCell(int columnIndex, Calendar value, int styleIndex)
throws IOException {
createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex);
return this;
}
#Override
public SpreadsheetWriter createCell(int columnIndex, Calendar value)
throws IOException {
createCell(columnIndex, value, -1);
return this;
}
}

Categories

Resources