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>
Related
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
I have a list of employee records in a table, i want to generate report out of it. Is there a way to generate and send the generated report in excel format to the browser in response.FYI I'm using Spring boot and reactjs.
You probably want to look at Apache POI
There are some examples of creating XLS[X] files in their developers guide
A quick example from there
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
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)
I want to disable GridLines in excel and put custom borders to excel cells using open xml in C#
I have tried with below code but is throwing exception when i open the excell,
the exception is "Repaired Part: /xl/worksheets/sheet.xml part with XML error. Load error. Line 1, column 0."
using (SpreadsheetDocument xl = SpreadsheetDocument.Create(sFile, SpreadsheetDocumentType.Workbook))
{
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetViews sheetViews = new SheetViews();
SheetView sheetView = new SheetView();
sheetView.ShowGridLines = new BooleanValue(false);
sheetViews.Append(sheetView);
ws.Append(sheetViews);
WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
//// add styles to sheet
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
//// add styles to sheet
////wbsp.Stylesheet = GenerateStyleSheet();
//wbsp.Stylesheet.Save();
Columns columns = new Columns();
columns.Append(CreateColumnData(1, 1, 25));
ws.Append(columns);
//// generate rows
SheetData sd = CreateSheetData(products);
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
MERGEiNITIALcELLS(wsp);
wb.Append(fv);
CreateSheet(wbp, wsp, wb);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
The WorkbookViewId property of the SheetView class is a required attribute/property. Try this:
SheetView sheetView = new SheetView();
sheetView.ShowGridLines = new BooleanValue(false);
sheetView.WorkbookViewId = 0;
sheetViews.Append(sheetView);
ws.Append(sheetViews);
That uses the 1st (default) workbook view. Don't worry, you don't have to explicitly create a WorkbookView child of the BookViews class, which is a child of Workbook. Unless you want to, of course. :)
I tried this way but it was failing but able to identify what is missing. By default when creating a spreadsheet from scratch, there is no default workbook view. So need to create new workbook view.
spreadSheet.WorkbookPart.Workbook = new Workbook(new BookViews(new WorkbookView()));
Then create sheet view.
worksheetPart.Worksheet = new Worksheet(new SheetViews(new SheetView(){WorkbookViewId=0,ShowGridLines=new BooleanValue(false)}), new SheetData());
NOTE: When create columns in the excel workbook, the elements should be created in a sequence. The sequence is
Sheet Views
Sheet View Formatting
Columns
Sheet Data
Enjoy Open XML SDK but Microsoft does not provide very powerfull documentation.
I want to copy an Excel Workbook with apache poi. The copy must be protected but the user should be able to resize the columns. I prepared a template and picked "columns format" on the first sheet in the template. When I use the following snippet
InputStream is = new FileInputStream(
new File(DIR, "template.xlsx"));
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(is);
XSSFSheet s = wb.getSheetAt(0);
s.protectSheet("");
FileOutputStream os = new FileOutputStream(new File(DIR, "test.xlsx"));
wb.write(os);
os.close();
I get a corrupt Excelsheet. I use apache poi 3.8 and Excel 2007.
Is there a workaround for protecting the sheets but allow to resize the columns?
Any help would be greatly appreciated
stephan
I know this is an old post, but I just solved this problem. You can use the following code:
//just initialize these
XSSFWorkbook xwb;
XSSFSheet xsheet;
xsheet.protectSheet("1234");
xsheet.getCTWorksheet().getSheetProtection().setFormatColumns(false);
xsheet.enableLocking();
xwb.lockStructure();
Hope this helps somebody in the future! :D