First of all, Please Pardon me for Poor Coding!
Requirement:
1. Create xls/xlsx Report in Memory from Database ResultSet (ie. Plain Text File should not be written to Disk).
2.Create ZIP on Disk From the xlsx file in Memory.
Environment:
WinXP SP2, JDK1.6_06, Zip4j1.3.1, poi3.8
I am using Apache's POI and Zip4j and am following Mr.Shrikant's Example published at "http://www.lingala.net/zip4j/forum/index.php?topic=257.0"
Observations:
1. This program Writes 27,842 bytes xlsx file to disk for sample data.
2. The same Workbook Creates ByteArrayOutputStream,baoStream of size is 49022bytes
3. After Encryption and Zipping It Creates File of Size 43,084 bytes.
4. While Extracting Zip file,
a) WinZip, throws Error "UnExpected End of File"
b) Winrar, throws "CRC Error"
Please correct me, wherever I am wrong and improve, wherever I am poor!
Thanks in Advance!
package zipconversion;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import net.lingala.zip4j.io.ZipOutputStream;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ZipCreationInMemory {
ZipOutputStream zos = null;
XSSFWorkbook workbook = null;
ByteArrayOutputStream baoStream = null;
String path = null;
String xlsxfileExtn = null;
String zipfileExtn = null;
String onlyFileName = null;
String xlsxFileName = null;
String zipFileName = null;
String xlsxFilePath = null;
String zipFilePath = null;
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void createXlsxFile() {
try {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh_mm_ss");
path = "D:\\abcd\\";
xlsxfileExtn = ".xlsx";
zipfileExtn = ".zip";
onlyFileName = "ReportData_".concat(timeFormat.format(new Date()));
xlsxFileName = onlyFileName + xlsxfileExtn;
zipFileName = onlyFileName + zipfileExtn;
xlsxFilePath = path + xlsxFileName;
zipFilePath = path + zipFileName;
FileOutputStream out = new FileOutputStream(new File(xlsxFilePath));
workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Report");
XSSFRow rowHead = sheet.createRow((short) 0);
XSSFCellStyle headStyle = workbook.createCellStyle();
XSSFFont headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
headStyle.setFont(headerFont);
headStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255)));
headStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFCellStyle oddStyle = workbook.createCellStyle();
oddStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(randInt(125, 255), randInt(125, 255), randInt(125, 255))));
oddStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
//JDBC CONFIGURATIONS
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
String dbURL = "jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_ID;password=PASSWORD";
Connection connection = DriverManager.getConnection(dbURL);
Statement st = connection.createStatement();
ResultSet resultSet = st.executeQuery("Select * from TABLE_NAME");
ResultSetMetaData metaData = resultSet.getMetaData();
int colCount = metaData.getColumnCount();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
for (int curColIndx = 0; curColIndx < colCount; curColIndx++) {
XSSFCell cell = rowHead.createCell((short) curColIndx);
cell.setCellStyle(headStyle);
cell.setCellValue(metaData.getColumnName(curColIndx + 1));
}
int index = 1;
while (resultSet.next()) {
XSSFRow row = sheet.createRow((short) index);
for (int curColIndx = 0; curColIndx < colCount; curColIndx++) {
XSSFCell cell = row.createCell((short) curColIndx);
if (index % 2 == 1) {
cell.setCellStyle(oddStyle);
}
else {
cell.setCellStyle(evenStyle);
}
int type = metaData.getColumnType(curColIndx + 1);
if (type == Types.TIMESTAMP) {
cell.setCellValue(sdf.format(resultSet.getDate(curColIndx + 1)));
} else if (type == Types.VARCHAR || type == Types.CHAR) {
cell.setCellValue(resultSet.getString(curColIndx + 1));
} else {
cell.setCellValue(resultSet.getLong(curColIndx + 1));
}
}
index++;
}
baoStream = new ByteArrayOutputStream();
try {
//This Writes 27,842 bytes xlsx file to disk for sample data.
workbook.write(out);
//same workbook is written to ByteArrayOutputStream()
workbook.write(baoStream);
//But, baoStream size is 49022bytes and After Encryption and Zipping It Creates File of Size 43,084 bytes.
System.out.println("baoStream.size() :" + baoStream.size());
try {
//byte[] bytesToWrite = getBytesFromFile();
byte[] bytesToWrite = baoStream.toByteArray();
InMemoryOutputStream inMemoryOutputStream = new InMemoryOutputStream();
zos = new ZipOutputStream(inMemoryOutputStream);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setFileNameInZip(xlsxFileName);
parameters.setSourceExternalStream(true);
zos.putNextEntry(null, parameters);
zos.write(bytesToWrite);
zos.closeEntry();
zos.finish();
zos.close();
// Write contents in our InMemoryOutputStream to a zip file to test if this worked
writeContentsToZipFile(inMemoryOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
out.close();
resultSet.close();
connection.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exception is :" + e.toString());
}
}
public ZipCreationInMemory() {
//testZipCreationInMemory();
createXlsxFile();
}
package zipconversion;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Writes the content to memory.
*
*/
public class InMemoryOutputStream extends OutputStream {
// As we cannot know the size of the zip file that is being created,
// we cannot maintain a byte array. We will copy all the bytes that
// gets passed in the write() method to a List. Once all writing is done,
// we can create a byte array from this List and this will be the content
// of the zip file
private List byteList;
// flag to keep track if the outputstream is closed
// no further write operations should be performed once this stream is closed
private boolean closed;
public InMemoryOutputStream() {
byteList = new ArrayList();
closed = false;
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("trying to write on a closed output stream");
}
byteList.add(Integer.toString(b));
}
public void write(byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(byte[] b, int off, int len) throws IOException {
if (closed) {
throw new IOException("trying to write on a closed output stream");
}
if (b != null && len > 0) {
for (int i = 0; i < len; i++) {
byteList.add(Byte.toString(b[i]));
}
}
}
public byte[] getZipContent() {
if (byteList.size() <= 0) {
return null;
}
byte[] zipContent = new byte[byteList.size()+1];
for (int i = 0; i < byteList.size(); i++) {
zipContent[i] = Byte.parseByte((String) byteList.get(i));
}
return zipContent;
}
public void close() throws IOException {
closed = true;
}
}
The bug is possible in method writeContentsToZipFile(inMemoryOutputStream), but you didn't post it's source code...
I think the implement of class InMemoryOutputStream is not required, it's not effective and cause more problem.
If you want to save the zip content to File, replace it with FileOutputStream
If you want to save the zip content in memory, replace it with ByteArrayInputStream inMemoryOutputStream = new ByteArrayInputStream(bytesToWrite.length);
Note: The first parameter of zos.putNextEntry(null, parameters) is null.
It works when parameters.setSourceExternalStream(true). Under this mode, file name and other parameters are supplied via ZipParameters.
Related
Iam using two different classes which generated the latest files in the directory, so this latest file is calling in the main method,but getting and error.
First latest file class file code:
package API_Automation.panaray;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import org.testng.annotations.Test;
public class DataBase_directory {
public static String getLatestFilePath() {
File folder = new File(".//Output_Files//Data_Base");
File[] listOfFiles = folder.listFiles();
File latestDir = null;
for (File file : listOfFiles) {
if (file.isDirectory() && (latestDir == null || file.lastModified() > latestDir.lastModified())) {
latestDir = file;
}
}
if (latestDir != null) {
//System.out.println("Latest directory: " + latestDir.getPath());
File directory = new File(latestDir.getPath());
File[] files = directory.listFiles();
// Sort files by last modified date
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified());
}
});
// Iterate through files and get the first file with .xlsx extension
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".xlsx")) {
return file.getPath();
// System.out.println(file.getPath());
}
}
}
return null;
}
}
Second latest file class file code:
package API_Automation.panaray;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import org.testng.annotations.Test;
public class Elastic_Search_directory {
public static String getLatestFilePath() {
File folder = new File(".//Output_Files//Elastic_Search");
File[] listOfFiles = folder.listFiles();
File latestDir = null;
for (File file : listOfFiles) {
if (file.isDirectory() && (latestDir == null || file.lastModified() > latestDir.lastModified())) {
latestDir = file;
}
}
if (latestDir != null) {
//System.out.println("Latest directory: " + latestDir.getPath());
File directory = new File(latestDir.getPath());
File[] files = directory.listFiles();
// Sort files by last modified date
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified());
}
});
// Iterate through files and get the first file with .xlsx extension
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".xlsx")) {
return file.getPath();
// System.out.println(file.getPath());
}
}
}
return null;
}
}
This is the main code which i am calling the filepath
package API_Automation.panaray;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Excel_Compare {
public void useFilepath(String filepath) throws IOException {
if (filepath == null) {
System.out.println("no file");
} else {
System.out.println("The filepath is" + filepath);
}
}
#Test
public void main(String[] args) throws IOException {
DataBase_directory DB_directory = new DataBase_directory();
String filepath1 = DB_directory.getLatestFilePath();
System.out.println(filepath1);
DataBase_directory ES_directory = new DataBase_directory();
String filepath2 = ES_directory.getLatestFilePath();
System.out.println(filepath2);
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = date.format(dateFormat);
DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm");
String formatedate = date.format(dateformat);
Path dir = Paths.get(".//Difference_Excel_Files//Excelfiles-" + formattedDate);
Files.createDirectories(dir);
try {
// Read the contents of both excel files
FileInputStream file1 = new FileInputStream(new File(filepath1));
FileInputStream file2 = new FileInputStream(new File(filepath2));
Workbook workbook1 = WorkbookFactory.create(file1);
Workbook workbook2 = WorkbookFactory.create(file2);
// Compare the contents of each cell
List<String[]> differences = new ArrayList<>();
for (int i = 0; i < workbook1.getNumberOfSheets(); i++) {
Sheet sheet1 = workbook1.getSheetAt(i);
Sheet sheet2 = workbook2.getSheetAt(i);
for (int j = 1; j < sheet1.getLastRowNum(); j++) {
Row row1 = sheet1.getRow(j);
Row row2 = sheet2.getRow(j);
for (int k = 1; k < row1.getLastCellNum(); k++) {
Cell cell1 = row1.getCell(k);
Cell cell2 = row2.getCell(k);
Cell cell3 = sheet1.getRow(0).getCell(k);
Cell cell4 = sheet1.getRow(j).getCell(0);
int type1 = cell1.getCellType();
int type2 = cell2.getCellType();
if (type1 == XSSFCell.CELL_TYPE_STRING & type2 == XSSFCell.CELL_TYPE_STRING) {
if (!cell1.getStringCellValue().equals(cell2.getStringCellValue())) {
differences.add(new String[] { sheet1.getSheetName(), cell4.getStringCellValue(),
cell1.getStringCellValue(), cell2.getStringCellValue(),
cell3.getStringCellValue() });
}
} else if (type1 == XSSFCell.CELL_TYPE_NUMERIC && type2 == XSSFCell.CELL_TYPE_NUMERIC) {
if (cell1.getNumericCellValue() != (cell2.getNumericCellValue())) {
differences.add(new String[] { sheet1.getSheetName(), cell4.getStringCellValue(),
cell1.getStringCellValue(), cell2.getStringCellValue(),
cell3.getStringCellValue() });
}
}
}
}
}
if (differences.contains(differences)) {
System.out.println("Data is not matching");
} else {
System.out.println("Data is matching");
}
// Write the differences to a new excel file
FileOutputStream fileOut = new FileOutputStream(dir + "//Difference" + "-" + formatedate + ".xlsx");
Workbook differencesWorkbook = new XSSFWorkbook();
Sheet differencesSheet = differencesWorkbook.createSheet("Differences");
if (differences.contains(differences)) {
for (int i = 0; i < differences.size(); i++) {
Row row = differencesSheet.createRow(i);
for (int j = 0; j < differences.get(i).length; j++) {
Cell cell = row.createCell(j);
cell.setCellValue(differences.get(i)[j]);
}
}
differencesWorkbook.write(fileOut);
fileOut.close();
} else {
differencesSheet.createRow(0).createCell(0).setCellValue("Data is matching");
differencesWorkbook.write(fileOut);
fileOut.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
The main method is to compare the two latestexcel file and paste the differnec between the excelf file.
I am attempting to download multiple excel files with one call. I have a stored procedure that returns data broken down by company, and for each company I need a separate excel file. Some of the values of the excel files are interdependent (so what is on the first excel file will go on to the second.
Except for a few functions which I have verified are working correctly, I've included the entirety of the code below. As it stands now the code runs exactly as it should, if I did not check the outputs I would think it was perfect, however where I expect to see two files downloaded I instead only get the first one. The second call to write to the ServletOutputStream does fire, but no file is downloaded.
Can anyone see what is wrong here? It isn't the file size, there should be a max of five records in each file, and I've downloaded single excel files before without issue.
package export;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.getFund;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
*
* #author mmarino
*/
public class NavExport extends HttpServlet {
String dateStr = "";
String ERDate = "";
Double absoluteTotal = 0.0;
Double iTotal = 0.0;
getFund g = new getFund();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String str = "";
Workbook wb = new HSSFWorkbook();
Workbook pWB = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet oSheet = wb.createSheet("Recon");
Sheet pSheet = pWB.createSheet("Recon");
String prevCompany = "";
dateStr = new Date().toString();
dateStr = new SimpleDateFormat("MM/dd/yyy").format(new Date());
ERDate = "ER" + dateStr.substring(6, 10) + dateStr.substring(0,2) + dateStr.substring(3,5);
try{
Connection conn = null;
ResultSet rs = null;
PreparedStatement prst = null;
String s = request.getParameter("ids");
String roll = request.getParameter("roll");
String[] ids = s.split("\\|");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connUrl = "My Connection URL";
conn = DriverManager.getConnection(connUrl);
String sql = "My SQL Query";
prst = conn.prepareStatement(sql);
rs = prst.executeQuery();
int pInt = 1;
int oInt = 1;
g.main();
while(rs.next()){
if(rs.getString("Company").equals("10")){
addRow(pSheet, rs, createHelper, pInt);
pInt++;
}else{
if(!prevCompany.equals(rs.getString("Company")) && !prevCompany.equals("") && !prevCompany.equals("10")){
writeWorkBook(wb, prevCompany, response);
oInt = 1;
wb = new HSSFWorkbook();
oSheet = wb.createSheet("Recon");
iTotal = 0.0;
}
prevCompany = rs.getString("Company");
addRow(oSheet, rs, createHelper, oInt);
iTotal += rs.getDouble("Approved");
oInt++;
}
absoluteTotal += rs.getDouble("Approved");
}// end rs.next();
if(!prevCompany.equals("10")){
addTopRow(oSheet, createHelper, prevCompany, iTotal);
writeWorkBook(wb, prevCompany, response);
}
addTopRow(pSheet, createHelper, "10", absoluteTotal);
writeWorkBook(pWB, "10", response);
}catch(Exception e){
str="Got exception: " + e.getMessage();
}
}
private void addTopRow(Sheet sheet, CreationHelper createHelper, String Company, Double amount){
try{
Row row = sheet.createRow((short)0);
row.createCell(0).setCellValue(createHelper.createRichTextString(dateStr));
row.createCell(1).setCellValue(createHelper.createRichTextString(""));
row.createCell(2).setCellValue(createHelper.createRichTextString(ERDate));
row.createCell(3).setCellValue(createHelper.createRichTextString("G/L Account"));
row.createCell(4).setCellValue(passSwitch(Company));
row.createCell(5).setCellValue(createHelper.createRichTextString(""));
row.createCell(6).setCellValue(createHelper.createRichTextString("1000-0000"));
row.createCell(7).setCellValue(createHelper.createRichTextString(""));
row.createCell(8).setCellValue(createHelper.createRichTextString(""));
row.createCell(9).setCellValue(createHelper.createRichTextString(""));
row.createCell(10).setCellValue(createHelper.createRichTextString(""));
row.createCell(11).setCellValue(createHelper.createRichTextString("Null"));
row.createCell(12).setCellValue(createHelper.createRichTextString(""));
row.createCell(13).setCellValue(createHelper.createRichTextString(""));
row.createCell(14).setCellValue(createHelper.createRichTextString(""));
row.createCell(15).setCellValue(createHelper.createRichTextString(""));
row.createCell(16).setCellValue(createHelper.createRichTextString(""));
row.createCell(17).setCellValue(amount);
row.createCell(18).setCellValue(createHelper.createRichTextString(""));
row.createCell(19).setCellValue(createHelper.createRichTextString(""));
row.createCell(20).setCellValue(createHelper.createRichTextString(""));
row.createCell(21).setCellValue(createHelper.createRichTextString("G/L Account"));
}catch(Exception e){
String error = e.toString();
}
}
private void addRow(Sheet sheet, ResultSet rs, CreationHelper createHelper, int i){
try{
Row row = sheet.createRow((short)i);
row.createCell(0).setCellValue(createHelper.createRichTextString(dateStr));
row.createCell(1).setCellValue(createHelper.createRichTextString(""));
row.createCell(2).setCellValue(createHelper.createRichTextString(ERDate));
row.createCell(3).setCellValue(createHelper.createRichTextString("G"));
row.createCell(4).setCellValue(rs.getString("Code"));
row.createCell(5).setCellValue(createHelper.createRichTextString(""));
row.createCell(6).setCellValue(createHelper.createRichTextString(g.getFundVar(rs.getString("Company") + ":" + rs.getString("Dept"))));
row.createCell(7).setCellValue(createHelper.createRichTextString(""));
row.createCell(8).setCellValue(createHelper.createRichTextString(""));
row.createCell(9).setCellValue(createHelper.createRichTextString(""));
row.createCell(10).setCellValue(createHelper.createRichTextString(""));
String emNum = rs.getString("EM");
while(emNum.length() != 9){
emNum = "0" + emNum;
}
emNum = "E" + emNum;
row.createCell(11).setCellValue(createHelper.createRichTextString(emNum));
row.createCell(12).setCellValue(createHelper.createRichTextString(""));
row.createCell(13).setCellValue(createHelper.createRichTextString(""));
row.createCell(14).setCellValue(createHelper.createRichTextString(""));
row.createCell(15).setCellValue(createHelper.createRichTextString(""));
row.createCell(16).setCellValue(createHelper.createRichTextString(""));
row.createCell(17).setCellValue(rs.getDouble("Approved"));
row.createCell(18).setCellValue(createHelper.createRichTextString(""));
row.createCell(19).setCellValue(createHelper.createRichTextString(""));
row.createCell(20).setCellValue(createHelper.createRichTextString(""));
row.createCell(21).setCellValue(createHelper.createRichTextString("G/L Account"));
}catch(Exception e){
String error = e.toString();
}
}
private void writeWorkBook(Workbook wb, String Company, HttpServletResponse response) {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=" + Company +".xls");
try {
ServletOutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Either you have to zip the Excel files and send as response OR you have it as a single excel file and use multiple sheets instead files
PDF files contain some French accent characters such as: e with some tick markt on top of them same with u or so.
When i check the PDF files before printing, i can see they are absolutely correct, i can read them in that PDF, i can zoom in and copy them perfectly fine.
But the moment Java touch it and prints it. Everything just does not work as it suppose to be.
How can i fix it please? the cloud version of that PDF is perfect but once my following code use to handle the file, then all those characters become broken in the print copy.
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaTray;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
public class PrintA4 {
public static boolean saveFile(URL url, String file) throws IOException {
boolean download_status = false;
System.out.println("open");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("reading file...");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
download_status = true;
System.out.println("downloaded");
return download_status;
}
public static void main(String[] args) throws IOException, PrinterException {
String downloaded_filename = "C:/pdf.pdf";
String download_pdf_from = "http://www.example.com/1.pdf" ;
String downloaded_filename_open_as_pdf = "C:\\pdf.pdf";
String printerNameDesired = "Brother HL-6180DW series";
PrintService[] services = PrinterJob.lookupPrintServices();
DocPrintJob docPrintJob = null;
for (int i = 0; i < services.length; i++) {
System.out.println(services[i]);
}
try{
URL url = new URL(download_pdf_from);
if(saveFile(url, downloaded_filename)) {
try {
PDDocument pdf = PDDocument.load(new File(downloaded_filename_open_as_pdf));
PrinterJob job = PrinterJob.getPrinterJob();
for (int i = 0; i < services.length; i++) {
if (services[i].getName().equalsIgnoreCase(printerNameDesired)) {
docPrintJob = services[i].createPrintJob();
}
}
job.setPrintService(docPrintJob.getPrintService());
job.setPageable(new PDFPageable(pdf));
PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
pset.add(MediaTray.BOTTOM);
job.print(pset);
} catch (Exception e) {
System.out.println("[FAIL]");
}
} else {
System.out.println("[FAIL]");
}
} catch (Exception ae) {
System.out.println("[FAIL]");
}
}
}
package com.otp.util;
import java.io.FileWriter; import java.io.IOException; import
java.text.SimpleDateFormat; import java.util.Date;
import com.otp.servlets.MessageServlet;
public class CDRWriter {
public FileWriter fileWriter = null;
static int lineCounter = 0;
static String fileName = null;
public void writeCDR(String cdrData) throws IOException {
if(lineCounter == 0){
fileName = createFile();
}else if(lineCounter>500){
String temp=fileName;
fileName = createFile();
lineCounter=0;
Runtime rt = Runtime.getRuntime();
String zipCmd="7z a "+"\""+MessageServlet.filePath+temp+".7z"+"\""+" "+"\""+MessageServlet.filePath+temp+"\"";
System.out.println("zipCmd = "+zipCmd);
rt.exec(zipCmd);
//rt.exec("del "+MessageServlet.filePath+temp);
}
System.out.println("cdr data = "+cdrData);
try {
if(lineCounter == 0){
fileWriter = new FileWriter(MessageServlet.filePath+fileName);
}else{
fileWriter = new FileWriter(MessageServlet.filePath+fileName,true);
}
System.out.println("cdr after if else condition ="+cdrData);
fileWriter.write(cdrData.toString());
System.out.println("cdr after write method ="+cdrData);
fileWriter.write("\r\n");
fileWriter.flush();
//fileWriter.close();
lineCounter++;
System.out.println("CDRWriter : lineCounter = "+lineCounter); } catch (IOException e) {
e.printStackTrace();
}
}// end of WriterCDR method
public String createFile() throws IOException {
SimpleDateFormat sdf = new
SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
String fileName ="GSMS_CDR_"+ sdf.format(new Date())+".txt" ;
return fileName;
}// end of the createFile method
}// end of CDRWriter class
I would do something like that:
import java.io.*;
import SevenZip.Compression.LZMA.*;
public class Create7Zip
{
public static void main(String[] args) throws Exception
{
// file to compress
File inputToCompress = new File(args[0]);
BufferedInputStream inputStream = new BufferedInputStream(new java.io.FileInputStream(inputToCompress));
// archive
File compressedOutput = new File(args[1] + ".7z");
BufferedOutputStream outputStream = new BufferedOutputStream(new java.io.FileOutputStream(compressedOutput));
Encoder encoder = new Encoder();
encoder.SetAlgorithm(2);
encoder.SetDictionarySize(8388608);
encoder.SetNumFastBytes(128);
encoder.SetMatchFinder(1);
encoder.SetLcLpPb(3,0,2);
encoder.SetEndMarkerMode(false);
encoder.WriteCoderProperties(outputStream);
long fileSize;
fileSize = inputToCompress.length();
for (int i = 0; i < 8; i++)
{
outputStream.write((int) (fileSize >>> (8 * i)) & 0xFF);
}
encoder.Code(inputStream, outputStream, -1, -1, null);
// free resources
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
The SKD for the SevenZip packages come from the offical SKD. Download it here ;).
Disclaimer: I believe, I found that snippet a while ago on the net...but I don't found the source anymore.
I am new to Java POI and i am trying to overwrite an excel file using Java POI.Let me make it clear, i don't want to open a new .xls file every time time i build the code however the code i wrote does it that way.The purpose for this is to, i will build the chart on excel and read the values for the chart from the database and write it to the excel file by using Java POI.Here is my code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");
HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Always use the same filename and when you run the program it will overwrite the file.
EDIT
If you want to modify an existing excel file then have a look HERE and scroll down to the section on "Reading or Modifying an existing file".
The problem is Apache POI doesn't support all features of Excel file format, including charts. So can not generate a chart with POI and when opening an existing Excel file with POI and modifying it, some of the current "objects" in the Excel file could be lost, as POI can't handle it and when writing, writes only the new information generated and existing one that can handle.
This is assumed by Apache as one of the flaws of POI.
We done similar processing of existing Excel file, filling new data onto it, but the existing Excel file contains only formatting styles and they are preserved using POI, but I think charts are very problematic. Trying ti filling data to update an existing chart is not possible with POI.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class UserInput {
public static Map getUserInput() throws InvalidFormatException, IOException {
String userName = System.getProperty("user.name");
String path = "";
int indexofColumn = 10;
Map inputFromExcel = new HashMap();
InputStream inp = new FileInputStream(path);
int ctr = 4;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
inputFromExcel.put("NBKID",cell.toString()) ;
row = sheet.getRow(ctr+1);
cell = row.getCell(indexofColumn);
inputFromExcel.put("Password", cell.toString());
row = sheet.getRow(ctr+2);
cell = row.getCell(indexofColumn);
inputFromExcel.put("NBKIDEmail",cell.toString());
row = sheet.getRow(ctr+3);
cell = row.getCell(indexofColumn);
inputFromExcel.put("sourceExcel" ,cell.toString());
} catch(Exception e) {
}
return inputFromExcel;
}
}
import java.util;
public class Main {
public static void main(String[] args) {
List<String> partyIdList = new ArrayList<String>();
List<String> phNoList = new ArrayList<String>();
String userName = System.getProperty("user.name");
String path = "";
try {
Map data = new HashMap(UserInput.getUserInput());
partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
WriteExcel.writeFile1(partyIdList, path,0,1);
WriteExcel.writeFile1(phNoList,path,1,0);
} catch (Exception e) {
throw new RuntimeException("Error while read excel Sheet" + e);
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
//System.out.println(path);
List<String> ItemList = new ArrayList();
InputStream inp = new FileInputStream(path);
int ctr = 0;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
ItemList.add(cell.toString());
// System.out.println(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
inp.close();
return ItemList;
}
}