I'm a newbie in zk programing.. and right now I'm using Eclipse Indigo to develop it.
I'm trying to import Excel .xlsx file, but it's not working.. I get error message org/apache/poi/ss/usermodel/WorkbookFactory
here is my .zul code
<?page title="import excel" contentType="text/html;charset=UTF-8"?><zk>
<window id="win" title="import excel" border="normal">
<listbox width="700px" id="box" mold="paging" pageSize="50" sizedByContent="true" span="true">
</listbox>
<button label="Load Excel to listview" upload="true,maxsize=300">
<attribute name="onUpload"><![CDATA[
import java.io.File;
import org.zkoss.io.Files;
import org.zkoss.util.media.Media;
String path = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
//alert(path);
Media media = event.getMedia();
Files.copy(new File(path+ "upload\\" + media.getName()), media.getStreamData());
com.function.ZKextend zke=new com.function.ZKextend();
//zke.ImportExcelProd(win,"box",media);
zke.ImportExcel(win,"box",media);
]]></attribute>
</button>
<separator />
</window>
</zk>
and this is my function to import the excel .xlsx file..
public void ImportExcel(Window nmWindow, String nmListbox, Media media) throws Exception{
/* We should now load excel objects and loop through the worksheet data */
FileInputStream input_document = new FileInputStream(new java.io.File("")+Executions.getCurrent().getDesktop().getWebApp().getRealPath("/")+"upload/"+media.getName());
Workbook my_xls_workbook = WorkbookFactory.create(input_document);
Sheet my_worksheet = my_xls_workbook.getSheetAt(0);
Iterator<Row> rowIterator = my_worksheet.iterator();
Listbox list = (Listbox) nmWindow.getFellow(nmListbox);
list.getItems().removeAll(list.getItems());
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
Listitem li = new Listitem();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_STRING: //handle string columns
cell.getStringCellValue();
li.setValue(cell.getStringCellValue());
li.appendChild(new Listcell(cell.getStringCellValue()));
break;
case Cell.CELL_TYPE_NUMERIC: //handle double data
cell.getNumericCellValue();
li.setValue(cell.getNumericCellValue());
li.appendChild(new Listcell(String.valueOf(cell.getNumericCellValue())));
break;
}
}
list.appendChild(li);
}
}
And I already added poi-3.8, poi-ooxml-3.8, poi-ooxml-schema-3.8,xmlbean-2.3 to my java build path library through add external JAR button in the project properties.
Is there anything that I miss so I get this error? Please help me, I'm really desperate here..
Thanks..
Related
My first WinUI 3 project. My second C# project. I have been able to get the FileSavePicker to work and display a dialog:
What I am going to show is a stub program created just to workout the issue I am having with the FileSavePicker.
Issue description: I don't know how to use the non-async method 'CreateReport()' with the async FileSavePicker.
I have tested CreateReport() method with the 'Create Report' button, and it successfully creates an excel file and successfully writes to the file (using EPPlus).
How can I make the CreateReport() method wait for the FileSavePicker to finish and then use the file.name from the FileSavePicker?
My attempts to do it produce an excel file, but when I attempt to open the file, excel gives me this error:
MainWindow:
XAML:
<Window
x:Class="App_WinUI3_FileSavePicker_Sandbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App_WinUI3_FileSavePicker_Sandbox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Width="800" BorderBrush="black" BorderThickness="8">
<TextBlock Text="Test of File Save Picker and Creating an Excel file" HorizontalAlignment="Center" Margin="10" FontSize="20"/>
<StackPanel Orientation="Horizontal">
<Button x:Name="myButton" Click="myButton_Click" Margin="10" Padding="10">Start File Save Picker</Button>
<Button x:Name="Button2" Click="Button2_Click" Margin="10" Padding="10" ToolTipService.ToolTip="Tests the creation of an excel file using a hardcoded filename and not using the File Save Picker" >Create Report</Button>
</StackPanel>
<TextBox x:Name="ReportStatus1" Header="Report Status 1" Margin="10" FontSize="20"/>
<TextBox x:Name="ReportStatus2" Header="Report Status 2" Margin="10" FontSize="20"/>
<TextBox x:Name="ReportStatus3" Header="Report Status 3" Margin="10" FontSize="20"/>
<TextBox x:Name="ReportStatus4" Header="Report Status 4" Margin="10" FontSize="20"/>
<TextBox x:Name="ReportStatus5" Header="Report Status 5" Margin="10" FontSize="20"/>
</StackPanel>
</Window>
C# Code behind
using Microsoft.UI.Xaml;
using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
using OfficeOpenXml;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace App_WinUI3_FileSavePicker_Sandbox
{
/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
// Retrieve the window handle (HWND) of the current WinUI 3 window.
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
// For EPPlus spreadsheet library for .NET
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
}
public string File_Name = string.Empty;
private void myButton_Click(object sender, RoutedEventArgs e)
{
DisplayReportSaveDialog("Report1");
CreateReport(File_Name);
}
private async void DisplayReportSaveDialog(string ReportName)
{
FileSavePicker savePicker = new FileSavePicker();
// Retrieve the window handle (HWND) of the current WinUI 3 window.
var window = (Application.Current as App)?.m_window as MainWindow;
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
// Initialize the folder picker with the window handle (HWND).
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, hWnd);
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Excel Workbook", new List<string>() { ".xlsx" });
// I don't want a text file. I need to create an excel file.
// savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
switch (ReportName)
{
case "Report1":
savePicker.SuggestedFileName = "Report1_" + String.Format("{0:MMddyyyy_HHmmss}", DateTime.Now) + ".xlsx";
break;
case "Report2":
savePicker.SuggestedFileName = "Report2_" + String.Format("{0:MMddyyyy_HHmmss}", DateTime.Now) + ".xlsx";
break;
}
// Display the file picker dialog by calling PickSaveFileAsync
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write the file name into the file.
// This is the sample code from the microsoft docs.
// It shows how to write simple text to a text file.
// It does work.
// Is there a similar way I can do this with my method 'CreateReport()'?
//await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
File_Name = file.Name;
// What does this do?
// Why did I add this?
//await file.DeleteAsync();
ReportStatus3.Text = $"path = {file.Path}";
ReportStatus4.Text = $"file_Name = {File_Name}";
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
ReportStatus1.Text = "File " + file.Name + " was saved....";
}
else
{
ReportStatus1.Text = "File " + file.Name + " couldn't be saved.";
}
}
else
{
ReportStatus2.Text = $"{ReportName} report cancelled.";
}
}
private void CreateReport(string filename)
{
try
{
filename = "c:\\sandbox\\" + filename;
ReportStatus5.Text = $"filename = {filename} - Message from (CreateReport())";
using (var package = new ExcelPackage(filename))
{
// EPPLUS - Add a new worksheet.
var ws = package.Workbook.Worksheets.Add($"EMB High Level Goals");
ws.Cells["A1"].Value = "1";
ws.Cells["A2"].Value = "2";
ws.Cells["B1"].Value = "Lenny";
ws.Cells["B2"].Value = "Created by App_WinUI3_FileSavePicker_Sandbox";
package.Save();
} // end using
ReportStatus3.Text = $"CreateReport: File {filename} was saved....";
}
catch (Exception e)
{
ReportStatus4.Text = $"CreateReport error: {e.Message}";
}
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
string filename = "Test_Report_" + String.Format("{0:MMddyyyy_HHmmss}", DateTime.Now) + ".xlsx";
CreateReport(filename);
}
}
}
Just remove commented Microsoft stuff:
//await FileIO.WriteTextAsync(file, file.Name);
//await file.DeleteAsync();
and instead of that call your own function:
CreateReport(file.Name);
You should await the DisplayReportSaveDialog before you call CreateReport.
For you to be able to do this, you need to change the return type of the former method from void to Task so you code will look like this:
private async void myButton_Click(object sender, RoutedEventArgs e)
{
await DisplayReportSaveDialog("Report1");
CreateReport(File_Name);
}
private async Task DisplayReportSaveDialog(string ReportName)
{
//same code as before...
}
private void CreateReport(string filename)
{
//same code as before...
}
I am trying to extract test output results in excel format. I want the results to be summarized in neat columns and row formats and want to display results graphically using a Pie chart.
To do this, I have used Apache POI API(Excel edits) and JFreeChart(for Pie chart creation).
I have been able to do all this, and the results are generated in .xls format.
When I tried to convert it to xlsx format after all of this, its doing the job, but the Pie chart and other excel stylings are missed to be written to .xlsx output file.
The code I have used for conversion from .xls to .xlsx is as follows:
package excelFileGenerate6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import com.aspose.cells.SaveFormat;
public class conversion_to_xlsx {
public static void main(String[] args) throws InvalidFormatException,
IOException {
String inpFn = "C:\\Users\\Username\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\report.xls";
String outFn = "C:\\Users\\Username\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\converted_report.xlsx";
FileInputStream in = new FileInputStream(inpFn);
try {
Workbook wbIn = new HSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new XSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(i);
//Sheet sOut = wbOut.getSheet(null);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(
cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
{
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
}
cellOut.setCellComment(cellIn.getCellComment());
// HSSFCellStyle cannot be cast to XSSFCellStyle
// cellOut.setCellStyle(cellIn.getCellStyle());
}
}
}
FileOutputStream out = new FileOutputStream(outF);
try {
wbOut.write(out);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
I have generated the excel reports and associated Pie chart using HSSF workbook style which gives the excel output in .xls format. Tried the online help to convert the HSSF objects to XSSF objects , but the pie chart creation gave a sun/image/codec error.
Attaching the Screenshots of code snippets and excel output files.
Any code/direction for converting my .xls results to .xlsx format will highly be of help for me..
Thanks
The code used to create Pie Chart :
package excelFileGenerate6;
import java.awt.Color;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.ChartUtilities;
import java.util.Iterator;
public class CreatePieChartExample {
public void createPie(String Filename) throws IOException {
/* Read Excel and the Chart Data */
FileInputStream chart_file_input = new FileInputStream(new File(Filename));
/* Read data into HSSFWorkbook */
HSSFWorkbook my_workbook = new HSSFWorkbook(chart_file_input);
/* This worksheet contains the Pie Chart Data */
HSSFSheet my_sheet = my_workbook.getSheetAt(0);
/* Create JFreeChart object that will hold the Pie Chart Data */
DefaultPieDataset my_pie_chart_data = new DefaultPieDataset();
/* We now iterate over the Excel Workbook data and Populate Pie Chart Data */
/* Create an Iterator object */
Iterator<Row> rowIterator = my_sheet.iterator();
/* Loop through worksheet data and populate Pie Chart Dataset */
String chart_label="a";
Number chart_data=0;
while(rowIterator.hasNext()) {
//Read Rows from Excel document
Row row = rowIterator.next();
//Read cells in Rows and get chart data
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
chart_data=cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
chart_label=cell.getStringCellValue();
break;
}
}
/* Add data to the data set */
my_pie_chart_data.setValue(chart_label,chart_data);
}
/* Create a logical chart object with the chart data collected */
JFreeChart myPieChart=ChartFactory.createPieChart("Test Results",my_pie_chart_data,true,true,false);
// Add custom colors
PiePlot plot = (PiePlot) myPieChart.getPlot();
//To create chart labels with only values on pie
PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{1}");
plot.setLabelGenerator(gen);
plot.setSectionPaint("Passed", Color.GREEN);
plot.setSectionPaint("Failed", Color.RED);
plot.setSectionPaint("Pending", Color.black);
plot.setSectionPaint("Total Time taken (ms)", Color.pink);
plot.setSectionPaint("Skipped", Color.blue);
plot.setSectionPaint("How many Sub headers are Passed", Color.yellow);
plot.setSectionPaint("Total TC's", Color.CYAN);
/* Specify the height and width of the Pie Chart */
int width=640; /* Width of the chart */
int height=480; /* Height of the chart */
float quality=1; /* Quality factor */
/* We don't want to create an intermediate file. So, we create a byte array output stream
and byte array input stream
And we pass the chart data directly to input stream through this */
/* Write chart as JPG to Output Stream */
ByteArrayOutputStream chart_out = new ByteArrayOutputStream();
ChartUtilities.writeChartAsJPEG(chart_out,quality,myPieChart,width,height);
/* We now read from the output stream and frame the input chart data */
InputStream feed_chart_to_excel=new ByteArrayInputStream(chart_out.toByteArray());
byte[] bytes = IOUtils.toByteArray(feed_chart_to_excel);
/* Add picture to workbook */
int my_picture_id = my_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
/* We can close Piped Input Stream. We don't need this */
feed_chart_to_excel.close();
/* Close PipedOutputStream also */
chart_out.close();
/* Create the drawing container */
HSSFPatriarch drawing = my_sheet.createDrawingPatriarch();
/* Create an anchor point */
ClientAnchor my_anchor = new HSSFClientAnchor();
/* Define top left corner, and we can resize picture suitable from there */
my_anchor.setCol1(4);
my_anchor.setRow1(5);
/* Invoke createPicture and pass the anchor point and ID */
HSSFPicture my_picture = drawing.createPicture(my_anchor, my_picture_id);
/* Call resize method, which resizes the image */
my_picture.resize();
/* Close the FileInputStream */
chart_file_input.close();
/* Write changes to the workbook */
FileOutputStream out = new FileOutputStream(new File(Filename));
my_workbook.write(out);
out.close();
}
public static void main(String args[]) throws IOException {
CreatePieChartExample chart = new CreatePieChartExample();
chart.createPie("C:\\Users\\user\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\report.xls");
}
}
The code used for .xls to .xlsx conversion:
package excelFileGenerate6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import com.aspose.cells.SaveFormat;
public class conversion_to_xlsx {
public static void main(String[] args) throws InvalidFormatException,
IOException {
String inpFn = "C:\\Users\\user\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\report.xls";
String outFn = "C:\\Users\\user\\JavaProjects\\workspace\\Sample2\\src\\excelFileGenerate6\\converted_report.xlsx";
FileInputStream in = new FileInputStream(inpFn);
try {
Workbook wbIn = new HSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new XSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(i);
//Sheet sOut = wbOut.getSheet(null);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(
cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
{
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
}
cellOut.setCellComment(cellIn.getCellComment());
// HSSFCellStyle cannot be cast to XSSFCellStyle
// cellOut.setCellStyle(cellIn.getCellStyle());
}
}
}
FileOutputStream out = new FileOutputStream(outF);
try {
wbOut.write(out);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
Iam trying to write a xls download for my Spring boot application. In order to generate the file Iam using POI. If I download the file directly from my Controller without passing it to the front-end like so:
//Wrote this one just for testing if the file is already corrupt here.
FileOutputStream fos = new FileOutputStream("C:\\dev\\directDownload.xls");
fos.write(byteArray);
fos.flush();
fos.close();
}
It works just fine and the file looks like this:
xls when downloaded from the backend without passing it to angular:
However thats not my goal. I intend to pass the Outputstream to my angular component. The Component calls a function from a service class. This class gets the response from the controller and passes it back to my component. In the UI the downloading dialog opens. The problem is, that the downloaded file looks like this (doesnt matter if its opened via excel or open office):
Currupt xls:
My Java Controller:
#CrossOrigin(exposedHeaders = "Content-Disposition")
#RequestMapping(value = "/report/file", produces = "application/vnd.ms-excel;charset=UTF-8")
public void getReportFile(#RequestParam(name = "projectNumber") final String projectNumber,
#RequestParam(name = "month") final int month, #RequestParam(name = "year") final int year,
#RequestParam(name = "employee") final int employee,
#RequestParam(name = "tsKey") final String tsKey,
final HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
String excelFileName = "test.xls";
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
excelFileName);
response.setHeader(headerKey, headerValue);
//Here I create the workbook that I want to download
ProjectMonthReport report = reportService.getReport(projectNumber, month, year);
//ExcelService builts the workbook using POI
Workbook workbook = excelService.exportExcel(report, employee, tsKey);
//The response is stored in an outputstream
OutputStream out = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
byte[] byteArray = ((HSSFWorkbook)workbook).getBytes();
out.write(byteArray);
out.flush();
out.close();
//Wrote this one just for testing if the file is already corrupt here. --> It's fine.
FileOutputStream fos = new FileOutputStream("C:\\dev\\directDownload.xls");
fos.write(byteArray);
fos.flush();
fos.close();
}
The Java Service method that builds the file using POI:
public Workbook exportExcel(final ProjectMonthReport report, final int employee, final String tsKey) throws IOException,
InvalidFormatException {
Workbook workbook = new HSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("Employee");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
Row headeRow = sheet.createRow(0);
Cell dateHeader = headeRow.createCell(0);
dateHeader.setCellValue("Datum");
Cell startHeader = headeRow.createCell(1);
startHeader.setCellValue("Beginn");
Cell endHeader = headeRow.createCell(2);
endHeader.setCellValue("Ende");
Cell activityHeader = headeRow.createCell(3);
activityHeader.setCellValue("Tätigkeitsbereit");
Cell cardHeader = headeRow.createCell(4);
cardHeader.setCellValue("Kartennummer");
List<WorkDescriptionDetail> details = report.getEmployees().get(employee).getKeyDetailMap().get(Integer.valueOf(tsKey)).getDetailList();
int counter = 1;
for (WorkDescriptionDetail detail : details) {
List <String> stringList= detail.toStringList();
Row row = sheet.createRow(counter);
Cell cellDate = row.createCell(0);
cellDate.setCellValue(stringList.get(0));
Cell cellStart = row.createCell(1);
cellStart.setCellValue(stringList.get(1));
Cell cellEnd = row.createCell(2);
cellEnd.setCellValue(stringList.get(2));
Cell cellActivity = row.createCell(3);
cellActivity.setCellValue(stringList.get(3));
counter ++;
}
return workbook;
}
My angular component:
saveFile(employee: string, tsKey:string) {
this.subscription = this.reportService.saveXlsFile(this.projectNumber, this.year, this.month, employee, tsKey)
.subscribe(response=> {
console.log(response);
let mediatype = 'application/vnd.ms-excel;charset=UTF-8';
const data = new Blob(["\ufeff",response.arrayBuffer()], {type: mediatype});
console.log(data);
saveAs(data, 'test.xls');
},
error => console.log("error downloading the file"));
}
The Ts Service Function that is called:
saveXlsFile(projectNumber:string, year:string, month:string, empId: string, tsKey:string) {
let params:URLSearchParams = new URLSearchParams();
params.set('projectNumber', projectNumber);
console.log(projectNumber);
params.set('month', month);
console.log(month);
params.set( 'year', year);
console.log(year);
params.set('employee', empId);
console.log(empId);
params.set('tsKey', tsKey);
console.log(tsKey);
return this.http.get(this.baseUrl + "/file", { search: params } );
}
I tried to retrieve the response via Postman and directly download the file. When I do that the file can't be opened by excel (Excel just crashed), however I can open the file in the OpenOffice version and it works fine. Its also not corrupted.
I've been searching the web for the last couple of days and I think it may be an enconding problem caused in the frontend. But maybe it is also SpringBoot thats playing me here. Any suggestions?
Thank you for your help!
Hey I found the solution to this problem yesterday myself. Adding the following in the angular service:
return this.http.get(this.baseUrl + "/file", { search: params, responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/vnd.ms-excel' });
});
After that you'll need to modify the component like so:
saveFile(employee: string, tsKey:string) {
this.subscription = this.reportService.saveXlsFile(this.projectNumber, this.year, this.month, employee, tsKey)
.subscribe(response=> {
console.log(response);
let mediatype = 'application/vnd.ms-excel';
saveAs(response, 'test.xlsx');
},
error => console.log("error downloading the file"));
}
So the Problem was that I was not getting a blob Object in my response....
I want to convert pdf data into excel data. I have converted pdf to text file and have removed unnecessary text inside .txt file but they are now in rows but I want them to become columnwise.
PDF file: chemistry-chemists.com/chemister/Spravochniki/handbook-of-aqueous-solubility-data-2010.pdf
Current state of excel file :
Required state of excel file:
PDFtables.com specialises in extracting tables from PDFs into Excel. This should be able to do what you are looking for :)
Have a look to Tabula a very efficient tool to convert table from pdf: https://github.com/tabulapdf/tabula
In ASP.NET you can use that code by the way
<div>
Upload PDF File :<asp:FileUpload ID="fuPdfUpload" runat="server" />
<asp:Button ID="btnExportToExcel" Text="Export To Excel" OnClick="ExportToExcel" runat="server" />
</div>
!!You have to implement iTextSharp from NuGet!!
protected void ExportToExcel(object sender, EventArgs e)
{
if (this.fuPdfUpload.HasFile)
{
string file = Path.GetFullPath(fuPdfUpload.PostedFile.FileName);
this.ExportPDFToExcel(file);
}
}
private void ExportPDFToExcel(string fileName)
{
StringBuilder text = new StringBuilder();
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new LocationTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.UTF8.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ReceiptExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(text);
Response.Flush();
Response.End();
}
I'm tring to to read large excel file (size~10MB,.xlsx) .
I'm using below code
Workbook xmlworkbook =WorkbookFactory.create(OPCPackage.openOrCreate(root_path_name_file));
But it's showing Heap memory issue.
I have also seen other solution on StackOverflow some of them given to increase the JVM but i dont want to increase jvm.
Issue 1) We can't use SXSSF (Streaming Usermodel API) because this is only for writing or creating new workbook.
My sole objective to get the number of NamedRange of sheet, Total number of sheet and their sheet name for large excel file.
If the requirement is only to get the named ranges and sheet names, then only the /xl/workbook.xml from the *.xlsx ZIPPackage must be parsed since those informations are all stored there.
This is possible by getting the appropriate PackagePart and parsing the XML from this. For parsing XML my favorite is using StAX.
Example code which gets all sheet names and defined named ranges:
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;
import javax.xml.namespace.QName;
import java.io.File;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class StaxReadOPCPackageParts {
public static void main(String[] args) {
try {
File file = new File("file.xlsx");
OPCPackage opcpackage = OPCPackage.open(file);
//get the workbook package part
PackagePart workbookpart = opcpackage.getPartsByName(Pattern.compile("/xl/workbook.xml")).get(0);
//create reader for package part
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(workbookpart.getInputStream());
List<String> sheetNames = new ArrayList<>();
Map<String, String> definedNames = new HashMap<>();
boolean isInDefinedName = false;
String sheetName = "";
String definedNameName = "";
StringBuffer definedNameFormula = new StringBuffer();
while(reader.hasNext()){ //loop over all XML in workbook.xml
XMLEvent event = (XMLEvent)reader.next();
if(event.isStartElement()) {
StartElement startElement = (StartElement)event;
QName startElementName = startElement.getName();
if(startElementName.getLocalPart().equalsIgnoreCase("sheet")) { //start element of sheet definition
Attribute attribute = startElement.getAttributeByName(new QName("name"));
sheetName = attribute.getValue();
sheetNames.add(sheetName);
} else if (startElementName.getLocalPart().equalsIgnoreCase("definedName")) { //start element of definedName
Attribute attribute = startElement.getAttributeByName(new QName("name"));
definedNameName = attribute.getValue();
isInDefinedName = true;
}
} else if(event.isCharacters() && isInDefinedName) { //character content of definedName == the formula
definedNameFormula.append(((Characters)event).getData());
} else if(event.isEndElement()) {
EndElement endElement = (EndElement)event;
QName endElementName = endElement.getName();
if(endElementName.getLocalPart().equalsIgnoreCase("definedName")) { //end element of definedName
definedNames.put(definedNameName, definedNameFormula.toString());
definedNameFormula = new StringBuffer();
isInDefinedName = false;
}
}
}
opcpackage.close();
System.out.println("Sheet names:");
for (String shName : sheetNames) {
System.out.println("Sheet name: " + shName);
}
System.out.println("Named ranges:");
for (String defName : definedNames.keySet()) {
System.out.println("Name: " + defName + ", Formula: " + definedNames.get(defName));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}