NPOI Multiple Sheets Error - excel

I am trying to create an EXCEL XLSX file in a .net webcontext.
I tried this code but as soon as I add more than 1 sheet my excel becomes corrupt.
I am using NPOI 2.1.3
XSSFWorkbook wb = new XSSFWorkbook();
wb.CreateSheet("sheet1");
wb.CreateSheet("sheet 2);
MemoryStream memoryStream = new MemoryStream();
wb.Write(memoryStream);
memoryStream.Close();
var buffer = memoryStream.GetBuffer();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.BinaryWrite(templateOutput);

When I use a FileStream the functionality works. (Multiple sheets)

Related

How to create a new sheet and write some data in the existing excel using selenium java

I tried the below code.
But it overwrite the existing sheet.
File f= new File(System.getProperty("user.dir")+"\\src\\test\\resources\\Exceldata.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet= workbook.createSheet("Sheet4");
HSSFRow row = worksheet.createRow(1);
HSSFCell cell= row.createCell(1);
cell.setCellValue("admin");
enter code here
workbook.write(f);
workbook.close();
Use FileInputStream instead of File and and object of XSSFWorkbook
I hope this function may help you,
public static void write(){
try
{
FileInputStream myxls = new FileInputStream(System.getProperty("user.dir")+"\\src\\test\\resources\\Exceldata.xls" );
HSSFWorkbook studentsSheet = new HSSFWorkbook(myxls);
workbook = new XSSFWorkbook(myxls );
workbook.createSheet(sheetname);
HSSFSheet worksheet = studentsSheet.getSheetAt(0);
a=worksheet.getLastRowNum();
System.out.println(a);
Row row = worksheet.createRow(++a);
row.createCell(1).setCellValue("");
myxls.close();
FileOutputStream output_file =new FileOutputStream(new File(System.getProperty("user.dir")+"\\src\\test\\resources\\Exceldata.xls"));
//write changes
workbook.write(output_file );
studentsSheet.write(output_file);
output_file.close();
System.out.println(" is successfully written");
}
Try calling this function from main maethod,
public static void main(String args[])
{
write();
}
Possible duplicate of Append Data in existing Excel file using apache poi in java and
How to add new sheets to existing excel workbook using apache POI?
I finally found out the solution. i had used poi jar 4.0 in which i could not succeed in writing data. I then downgraded the jar version to 3.14 and i works perfectly

Groovy/Grails document download

I'm currently working on a web application using grails. One of the requirements is to generate excel timesheets and download it afterword.
This is my code for downloading from grails controller.
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-Disposition","attachment;filename=name.xls")
response.outputStream << wb.bytes
response.outputStream.flush()
But my excel file is corrupted. I can open it using open office, but doesn't work using microsoft office or google drive. Looks like the content of the xls file is not well formatted.
If I save document instead of downloading everything is ok.
FileOutputStream fileOut = new FileOutputStream("name.xls")
wb.write(fileOut)
fileOut.close()
I cannot figured out why the file content is corrupted when downloaded as byte array.
Grails version - 2.3.7
Apache poi version - 3.13
Thanks in advance,
Method code
def generate(){
TimeSheetExportWrapper timeSheet = new TimeSheetExportWrapper()
bindData(timeSheet, params.ts)
HSSFWorkbook wb = excelExportService.createExcelTimeSheet(getCurrentTenant(), timeSheet, getCurrentTimezone())
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-Disposition", "attachment;filename=${timeSheet.proposedFileName}")
response.outputStream << wb.bytes
response.outputStream.flush()
}
There are a few things that you should be doing:
First, set the content length: response.setHeader("Content-Length", "${wb.bytes.length}")
Secondly, close the output: response.outputStream.close()
And finally, make sure you return null to ensure Grails does not attempt to render a view.
def generate(){
TimeSheetExportWrapper timeSheet = new TimeSheetExportWrapper()
bindData(timeSheet, params.ts)
HSSFWorkbook wb = excelExportService.createExcelTimeSheet(getCurrentTenant(), timeSheet, getCurrentTimezone())
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-Length", "${wb.bytes.length}")
response.setHeader("Content-Disposition", "attachment;filename=${timeSheet.proposedFileName}")
response.outputStream << wb.bytes
response.outputStream.flush()
response.outputStream.close()
return null
}

Modifying an Excel File in Google Drive with Apache POI

I need to modify some cells of an Excel file stored in Google Drive. I'm using Apache POI to manipulate the Excel file and I can read and modify the file, but when I commit it to Google Drive it seems to work, it returns a success code but the file is not changed in Drive. The function I'm using to save the file is:
ParcelFileDescriptor file=result.getDriveContents().getParcelFileDescriptor();
InputStream in=new FileInputStream(file.getFileDescriptor());
HSSFWorkbook wb = new HSSFWorkbook(in);
for(Componente c:listaComponentes){
HSSFSheet sheet=wb.getSheetAt(c.getHoja());
HSSFRow fila=sheet.getRow(c.getFila());
fila.getCell(celdaSerie).setCellValue(c.getSerie());
}
FileOutputStream fileOut = new FileOutputStream(file.getFileDescriptor());
wb.write(fileOut);
result.getDriveContents().commit(mGoogleApiClient, null);

chart formatting lost when save as xlsx in NPOI

I have a template xlsx, called "book3.xlsx" that contains a pre-formatted chart. All I want to do is to read my template xlsx and modify some cells and write out the a xlsx ("test.xlsx")
A strange thing happens here, if i open the result xlsx the format of the chart has changed... It has different coloring, axis is missing etc. When I used xls file format it was fine, but we should use xlsx. Anyone noticed this issue?
var file = new FileStream(#"book3.xlsx", FileMode.Open, FileAccess.Read);
var workbook = new XSSFWorkbook(file);
using (var fs = new FileStream(#"test.xlsx", FileMode.Create))
{
workbook.Write(fs);
}

Creating excel sheet from template in Java, new versions of Excel

I found the following code to create a excel sheet from an existing template with formats and add data to it and save it to a new file
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream("template.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs, true);
Will load an xls, preserving its structure (macros included). You can then modify it,
HSSFSheet sheet1 = wb.getSheet("Data"); ...
and then save it.
FileOutputStream fileOut = new FileOutputStream("new.xls");
wb.write(fileOut);
fileOut.close();
This works absolutely fine. But my issue is that I am dealing with new versions of excel now. So I need to develop a similar code to handle new version of template. Can someone suggest how can I do this? I tried changing HSSWorkbook to XSSFWorkbook. however XSSFWorkbook doesn't have a constructor that lets me pass a boolean. Also. when i tried it, it copies the data but the rows with data do not retain the formatting of the columns that the template has.
This should work fine (though it's always best to use the latest version of POI for all the bug fixes):
Workbook wb = new XSSFWorkbook( OPCPackage.open("template.xlsx") );
Sheet sheet = wb.getSheetAt(0);
// Make changes to the sheet
sheet.getRow(2).getCell(0).setCellValue("Changed value"); // For example
// All done
FileOutputStream fileOut = new FileOutputStream("new.xls");
wb.write(fileOut);
fileOut.close();
If you code against the interfaces, then you can just swap between HSSF and XSSF in your constructor, and have your code work for both formats
I used XSSF and it is working fine.
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("template.xlsx"));
FileOutputStream fileOut = new FileOutputStream("new.xlsx");
//Sheet mySheet = wb.getSheetAt(0);
XSSFSheet sheet1 = wb.getSheet("Summary");
XSSFRow row = sheet1.getRow(15);
XSSFCell cell = row.getCell(3);
cell.setCellValue("Bharthan");
wb.write(fileOut);
log.info("Written xls file");
fileOut.close();
Just need to add this dependency in pom.xml of maven
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8-beta4</version>
</dependency>

Resources