Error reading zip file containing an excel file

Hi all,
Using servlets I am able to zip an excel file using java.util.zip package. The excel file is created using POI API.
While I save and extract the zip file on my machine and then open the file in MS Excel. Excel pops a message saying "MS Office Excel has encountered a problem and need to close" and it gives me an option to "Recover my work and restart MS Office Excel". I select the option and then MS Excel does a document recovery and I am able to view my data. I get an excel repair log file saying as follows
"Microsoft Office Excel File Repair Log
Errors were detected in file 'C:\Documents and Settings\JohnDoe\Desktop\excel\test.xls'
The following is a list of repairs:
Damage to the file was so extensive that repairs were not possible. Excel attempted to recover your formulas and values, but some data may have been lost or corrupted.
I have attached my servlet code down below I suspect there is a problem with PrintWriter to output or do I need to use OutputStream to write excel data.
Below is my servlet code:
import java.io.*;
import javax.servlet.*;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.zip.*;
import java.net.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.util.*;
public class ZipServlet extends HttpServlet {
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse)
     public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
          makeZip(request, response, "GET");
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
               makeZip(request, response, "POST");
     public void makeZip(HttpServletRequest request, HttpServletResponse response, String methodGetPost) {
          Logger logger = Logger.getLogger(ZipServlet.class);
          try
               int id=1;
               ServletContext sc = getServletContext();
     HttpSession session = request.getSession();          
               ConnectionPoolManager cpm = (ConnectionPoolManager)sc.getAttribute("CONNECTION_POOL_MANAGER");
               ConnectionPool cp = cpm.getConnectionPool(id);
          createTestExcelZip(request,response,methodGetPost,session);
          } catch (Exception e2) {
     public void createTestExcelZip(HttpServletRequest request, HttpServletResponse response,
               String methodGetPost,HttpSession session
               )throws ServletException, IOException
          Logger logger = Logger.getLogger(ZipServlet.class);
          try
          {      //Create an Excel Workbook and placing value "Test" in the first cell
               HSSFWorkbook wb = new HSSFWorkbook();
               HSSFSheet sheet = wb.createSheet("new sheet");
               HSSFCell cell=null;
               HSSFRow row = sheet.createRow((short) 0);
               short column = 0;
               cell = row.createCell(column);
               cell.setCellValue(new HSSFRichTextString("Test"));
               HSSFCellStyle fontStyle = wb.createCellStyle();
          HSSFFont f = wb.createFont();
          f.setFontHeight((short) 200);
          f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
          fontStyle.setFont(f);
          cell.setCellStyle(fontStyle);
          response.setContentType("application/zip");
               response.setHeader("Content-Disposition","attachment; filename=zipExcelRecordFiles.zip;");
               int BUFFER = 2048;
               byte buf[]=new byte[300000];
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               ZipOutputStream zos = new ZipOutputStream( baos );
               ByteArrayInputStream is = null;
               BufferedInputStream origin = null;
               byte[] b = null;
               String fileName = null;
               b = wb.getBytes();
               fileName = "testExcelRecords.xls";
               try
               is = new ByteArrayInputStream(b);
               origin = new BufferedInputStream(is, BUFFER);
               zos.putNextEntry(new ZipEntry(fileName)); // Add ZIP entry to output stream.
          int count;
          while((count = origin.read(buf, 0, BUFFER)) != -1)
          zos.write(buf, 0, count);
          zos.closeEntry(); // Complete the entry
               is.close();
               }catch(Exception e)
                    logger.error(e);
               zos.close();
          PrintWriter pr = response.getWriter();
               pr.write(baos.toString("ISO-8859-1"));
               pr.close();
          catch(Exception e)
          logger.error(e);     
     * @see javax.servlet.GenericServlet#destroy()
     public void destroy() {
Any help would be appreciated.
Regards
jdcunha

Jdcunha,
I am new to the field but encountered the same problem and recently found a solution. Hope this helps.
For my project I wanted to create individual Excel 2003 workbooks for each file I created. Excel would give me the same error it gave you when I used the same HSSFWorkbook object. I tried creating a new Workbook object each time, but ran into the same issue.
I ended up fixing the error by creating a new instance of my write-to-excel class each time I wanted to create a new workbook, instead of just recreating a new HSSFWorkbook object. It works perfectly and the Excel errors don't show. It may also be important to note I used OutputStream, I did not try it with printwriter.

Similar Messages

  • Error reading zip file in Java 6

    We have a bespoke installer program that fails, intermittently, in Java 6 on Windows. After installing some files, it then fails with a stack trace like this:
    java.util.zip.ZipException: error reading zip file
         at java.util.zip.ZipFile.read(Native Method)
         at java.util.zip.ZipFile.access$1200(ZipFile.java:29)
         at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:447)
         at java.util.zip.ZipFile$1.fill(ZipFile.java:230)
         at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:141)
         at java.io.FilterInputStream.read(FilterInputStream.java:90)
         at com.XXXX.trent.installer.Installer.writeStreamToFile(Unknown Source)
         at com.XXXX.trent.installer.Installer.installFile(Unknown Source)
         at com.XXXX.trent.installer.PatchFileInstaller.installFile(Unknown Source)
         at com.XXXX.trent.installer.PatchFileInstaller.installFiles(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller$TpfAction.run(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller.runActions(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller.install(Unknown Source)
         at com.XXXX.trent.installer.TrentInstall$SoftwareInstallStage.install(Unknown Source)
         at com.XXXX.trent.installer.TrentInstall$UpgradeInstallWorker.install(Unknown Source)
         at com.XXXX.trent.installer.PatchInstall$InstallWorker.construct(Unknown Source)
         at com.XXXX.trent.utils.SwingWorker$2.run(Unknown Source)
         at java.lang.Thread.run(Thread.java:619)The same code works in Java 5 on the same environments that it now fails in Java 6 (1.6.0_16).
    Any ideas?
    Thanks.

    gimbal2 wrote:
    it is not weird, it is a bug in the application. Don't let the upgrade from Java 5 to Java 6 make you believe otherwise.It's a singularly bad exception message though. I would have thought that something from java.util might be a bit more explicit about what the problem is.
    Winston

  • How to read the content of this excel file in LV

    Hi could you please let me know how can I read the content of this excel file using the Read From Speardsheet function. It contains text and numbers
    Thanks
    The excel file is attached
    Attachments:
    Datalogging.zip ‏307 KB

    Check attached VI.
    I am not allergic to Kudos, in fact I love Kudos.
     Make your LabVIEW experience more CONVENIENT.
    Attachments:
    ReadFromExcel.vi ‏27 KB

  • Need to read each sheet of an excel file and pass it to XI

    Hi
    Actually i need to read each sheet of an excel file and pass it to XI and will create one xml file .I am able to read the excel file by writting a custom module and it is generating the xml output from XI.But my requierment is to read the excel file and create the xml with the sheet name of the excel.suppose sheet name is sheet1, the xml file name will be  sheet1.xml.if sheet name is sheet2 the xml file name will be  sheet2 and so on....how can i pass this parameter from NWDS to SAP XI s i am passing the string which contains the sheet data.

    If I understood correct you are already reading the XLS and creating the XML (not sure if this is a separate executing body out side of XI). Are you using any sort of Object Modal in Java to read the XML? I am aware of Visual Basic object modal for Excel but not sure if one is available in Java from Microsoft.
    The Object modal that you are using must be providing an iterator to loop through each of the sheet in the Excel workbook and you should be able to create the XMLs as you desired.
    I would be glad to look at you module if you are doing it once the XI file adapter has picked up the excel file.
    VJ

  • How can i Read the Data from such Excel files?

    Dear All,
            Here I am attaching an excel file in which all the datat cells have more than one data, can anybody tell me, how to read from such kind of excel files?
    Thanks in Advance & Happy New Year,
    Rujuta

    Greetings Ruju,
    Here is what I do to read such a file:
    I first save the Excel file (xls) as CSV file (which is easier to handle: Comma Seperated Values) .. Open the file using Excel and save it CSV.
    Then using the code attached I get all these values in a string array.
    Hope this helps
    Ayman Mohammad Metwally
    Automation Engineer
    Egypt - Cairo
    Attachments:
    CSV2ARRAY.vi ‏29 KB

  • How to save query result on the file server as excel file?

    Hi everyone,
    I need to save the the query result on the file server as excel file.
    Do you have any idees how can I do it?
    Regards
    Erwin

    i dont think you can save as excel file but you can save it as CSV use APD or RSCRM BAPI for this

  • Can we combine multiple excel files into one excel file using SSIS?

    I have a bunch of excel files in a specified folder. I wanted to combine all the excel files into one excel file by adding additional tabs in one excel file. Can I do this using SSIS?
             OR
    I know using macro we can combine multiple excel files. Can we run a excel macro in SSIS? Please help me.
    Actually the complete package is this:
    Step1: Using FTP task I'm downloading the bunch of excel files into a folder.
    Step2: Above implementation is the second step that I have to do.  

    You can do it in two steps
    1. First get all data from excel sheets to a sql staging table. For that you need to use a looping logic as explained in below link (you dont required the additional logic used for checking file name etc in below example as you need all files). Also make
    source as excel instead of flat file
    http://visakhm.blogspot.in/2012/05/package-to-implement-daily-processing.html
    2. Once you get the data onto a single table, use below to get it exported to multiple sheets within same excel destination file
    http://visakhm.blogspot.in/2013/09/exporting-sqlserver-data-to-multiple.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • I have tried to vonvert a PDF file to an excell file, but it appears to still be a PDF.

    I have tried to vonvert a PDF file to an excell file, but it appears to still be a PDF.

    If you have a mac, when you Sync your iphone, it will automaticly Sync your contacts to Adress book on the Mac. If this is not the case, you can take a look in iCloud, maybe you have backed them up there.
    This is not a problem caused by iOS6, but by iCloud... it has happend to alot of people, its due to pressing the wrong OK or CANCEL button at a certain pop-up.
    Good luck

  • Webutil error while trying to open an excel file

    Hi, I´m using oracle forms to read an excel file, I have two installations in different servers using oracle app server 9.04 and in one of this installations while trying to read an excel file i get the following error message in the java console:
    2006-jul-14 10:45:27.718 ERROR>WUO-708 [OleFunctions.get_obj_property()] No se ha podido obtener la propiedad: Workbooks; Excepción
    com.jacob.com.ComFailException: A COM exception has been encountered:
    At Invoke of: Workbooks
    Description: An unknown COM error has occured.
    2006-jul-14 10:45:36.140 WUO[getProperty()] Getting property WUO_OLE2_CREATE_ARGLIST
    2006-jul-14 10:45:37.781 WUO[setProperty()] Setting property WUO_OLE2_HANDLE to 2
    2006-jul-14 10:45:37.781 WUO[setProperty()] Setting property WUO_OLE2_ADD_ARG to SD:\UPLOADS\FILE.xls
    I dont really know where to start to try and solve this issue, any help is greatly appreciated
    Thanks
    Hi, I´m using oracle forms to read an excel file, I have two installations in different servers using oracle app server 9.04 and in one of this installations while trying to read an excel file i get the following error message in the java console:
    2006-jul-14 10:45:27.718 ERROR>WUO-708 [OleFunctions.get_obj_property()] No se ha podido obtener la propiedad: Workbooks; Exception
    com.jacob.com.ComFailException: A COM exception has been encountered:
    At Invoke of: Workbooks
    Description: An unknown COM error has occured.
    2006-jul-14 10:45:36.140 WUO[getProperty()] Getting property WUO_OLE2_CREATE_ARGLIST
    2006-jul-14 10:45:37.781 WUO[setProperty()] Setting property WUO_OLE2_HANDLE to 2
    2006-jul-14 10:45:37.781 WUO[setProperty()] Setting property WUO_OLE2_ADD_ARG to SD:\UPLOADS\FILE.xls
    I dont really know where to start to try and solve this issue, any help is greatly appreciated
    Thanks

    I created a system DSN named odbc_excel. Then, I created a file named initexcelsid.ora with the following arguments:
    HS_FDS_CONNECT_INFO = odbc_excel
    HS_AUTOREGISTER = TRUE
    HS_DB_NAME = dg4odbc
    In the location, I put excelsid in the Service_Name entry. Do you need me to post the listener.ora file or something else?
    Thank you.

  • Intermittent Error 41106 Error when trying to open an Excel file.

    I am having an intermittent problem while opening an Excel file.  The problem only occurs occasionally during execution of my program.  My program has a cluster of buttons each button opens a sub VI that is part of a calibration process.  The first VI generates an EXCEL filename that is used to save all calibration data.  A template is opened, data is placed in this template, and then it is saved under the generated filename.  Most of the time this seems to work fine, but every once in a while I receive a -41106 error indicating that Microsoft EXCEL did not open.  As far as I can tell when I run each sub VI independently they work fine and no errors are generated.  Does anyone know why this might be happening?  I would appreciate any help.
    Thanks 

    What version of LabVIEW and the Report Generation Toolkit are you using?  I remember adding some code in the 1.1 version of the toolkit to attempt to avoid some Microsoft Excel latencies with opening/closing the application repeatedly, but it was by no means fool proof, since Excel sometimes takes its sweet time leaving memory when the application exits.  Without knowing any more specifics, my best suggestion is for you to add a small delay between successive operations regarding opening/closing Excel and see if that helps.  Also, if you could post a simple VI that demonstrates the behavior, that would be extra helpful.
    Oh yeah, and another suggestion would be to open one report reference at the beginning of your program, and use this reference through the whole thing...I understand that this might not be possible, though, if you're opening different worksheets throughout the course of your application running.
    Good luck,
    -D
    P.S. - For those of you reading this wondering why I would automatically assume MegaMan is using the Report Generation Toolkit, he cites error -41106, which is an error specific to this toolkit.
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman

  • How can i send a folder containing multiple excel file to a mail address?

    hi ,
           i have report showing details sales report. Key field is customer id.  my requirement is to send the output of this report as excel file  to a mail id according to customer id. suppose there are 100 customer id , so 100 excel sheet will go to the mail. I have done it. But now  i want to send a folder or zip folder that's containing all the excel file to the mail id  so the mail user can download that folder at a time containg all the excel file. Is it possible ? if then how.  i have used cl_bcs , cl_document_bcs and if_recipient_bcs  these class and interface.
    I need your suggestion.

    Hi Sandipan,
    You can use some of this classes: CL_ABAP_ZIP or CL_ABAP_GZIP
    For example:
    DATA: OBJ_ZIP TYPE REF TO CL_ABAP_ZIP,
                ZIP_FILE  TYPE XSTRING.
    CREATE OBJECT OBJ_ZIP.
    OBJ_ZIP->ADD( NAME = <file_name>   CONTENT = CONTENT ).
    OBJ_ZIP->ADD( NAME = <file_name2> CONTENT = CONTENT ).
    ZIP_FILE = OBJ_ZIP->SAVE( ).
    You can also visit this Otto Frost detailed post on GZIP:
    http://wiki.sdn.sap.com/wiki/display/profile/GZIP
    I hope that helps.
    Regards,
    John
    Edited by: John Smith on Feb 5, 2012 2:21 PM

  • Can't read special characters in an excel file using JDBC

    Hi! I 've a code to read an excel file using JDBC-ODBC bridge. I can read the values, but any special characters is readed wrong, just symbols. The special characters are of spanish language. This is my code:
                    Locale currentLocale;
              currentLocale = new Locale("es", "MX");
              Locale.setDefault(currentLocale);
                   Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
                   c = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=comisionesperfiles.xls");
                   stmnt = c.createStatement();
                   String query = "Select * from [Hoja1$]" ;
                   ResultSet rs = stmnt.executeQuery( query );
                   while( rs.next() ){
                        String valor = rs.getString(2) ;
                        if(valor != null && !"null".equalsIgnoreCase(valor)){
                             if(!comisiones.contains(valor)){
                                  System.out.println(valor);
                                  comisiones.add( valor );
                   rs.close();
                   stmnt.close();As you can see, I've tried to set the locale, but it didn't work.
    I'm using Excel 2003, Java Version 1.4.2_07 and Windows XP Professional (in latin american spanish).
    Hope someone can help me!

    FYI: Apache's POI can read/write Excel files in Java:
    http://jakarta.apache.org/poi/index.html

  • Unable to read E$ table records into excel file in linux machine

    Hi
    I am using below code in ODI procedure to read E$ table record and store it in excel file
    ODI Procedure: Technology=Java Beanshall and Command on Target I written below code and placed it in CKM Oracle KM
    <@
    String OS = System.getProperty("os.name").toLowerCase();
    String v_path="";
    if((OS.indexOf("win") >= 0))
    v_path="D:\Unload_Dir\<%=snpRef.getSession("SESS_NO")%>.xlsx";
    else if (OS.indexOf("mac") >= 0)
    v_path="path details";
    else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 )
    v_path="/odi_a/oracle/Middleware/logs/wcds/odi_logs/<%=snpRef.getSession("SESS_NO")%>.xlsx";
    else if (OS.indexOf("sunos") >= 0)
    v_path="soliaris path";
    @>
    OdiSqlUnload "-FILE=<@=v_path@>" "-DRIVER=<%=odiRef.getInfo("DEST_JAVA_DRIVER")%>" "-URL=<%=odiRef.getInfo("DEST_JAVA_URL")%>" "-USER=<%=odiRef.getInfo("DEST_USER_NAME")%>" "-PASS=<%=odiRef.getInfo("DEST_ENCODED_PASS")%>" "-FILE_FORMAT=VARIABLE" "-ROW_SEP=\r\n" "-DATE_FORMAT=yyyy/MM/dd HH:mm:ss" "-CHARSET_ENCODING=ISO8859_1" "-XML_CHARSET_ENCODING=ISO-8859-1"
    select * from <%=odiRef.getTable("L","ERR_NAME", "W")%>
    But is not reading the data into .xlsx file ,
    Please help me it is very urgent
    Can I use below code
    String os = "";
    if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
    os = "windows";
    } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
    os = "linux";
    } else if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
    os = "mac";
    T
    his is high priority, please help me urgent
    Regards,
    Phanikanth
    Edited by: Phanikanth on Feb 28, 2013 5:43 AM
    Edited by: Phanikanth on Feb 28, 2013 6:00 AM
    Edited by: Phanikanth on Feb 28, 2013 7:42 AM

    Hi,
    can you describe what is happening when you run the ODI procedure described below:
    - Does the procedure fail with an error, if yes, which error(full details)?
    - Does the procedure pass but no xslx file is been created?
    - Does the procedure pass and an xslx file is been created, but Excel can't read it? If yes, what is the structure of the xslx file when read in an editor?
    What I can see from your code below is that you have choosen -FILE_FORMAT=VARIABLE, but the XSLX format is supposed to be XML.
    Regards,
    Alex

  • How do read the data of the excel file line by line to the waveform?

    hello:
          i am a beginner.so i hope that  you can give me a small example。the data of the excel  file i
     have given out.
    looking for your replys!!!
    Solved!
    Go to Solution.
    Attachments:
    数据.xls ‏14 KB

    try this. best of luck
    Gaurav k
    CLD Certified !!!!!
    Do not forget to Mark solution and to give Kudo if problem is solved.
    Attachments:
    Read column.zip ‏26 KB

  • Read all cells from an Excel file?

    Hi!
    I'm trying to read every cell from an Excel spreadsheet file, e.g.
    test.xls. The example in the NI Dev Zone (ActiveX Read Cells from
    Excel2000 VI) works if you know in advance what the first and last cell
    are, e.g. A1 and E453.
    The trouble is that the number of rows & columns in the file will vary;
    the last cell of 1 file might be E453, another might end at F29.
    How can I programmatically read every cell in the file? I thought of 2
    approaches:
    1: Find an ActiveX property that returns the last cell (or last row and
    last column).
    2: Use some other way to read an .xls file, maybe not by launching Excel
    but by using another program ...
    The NI applications engineer couldn't find a reasonably easy solution,
    so I'd w
    elcome any input.
    Thanks! Mark

    Mark,
    I haven't been able to find out if there is an ActiveX property or method the excel exposes to be able to do this ... searching on http://msdn.microsoft.com didn't return anything particularly useful.
    I've tried this sort of thing a couple of different ways. The simplest is if I have control over the file generation code, in that case I've just used the first row A1 and B1 to contain the number or rows and columns respectively and moved on from there.
    If that isn't a possibility then you could enter nonsense data around the acutal data and then look for that and then resize the array. This could get pretty slow if you read row by row, I've somtimes read chuncks of rows and then adjusted the next read and and combined arrays. With a large data set the memory and s
    peed implications do need to be looked at.
    The last thing is what you are referring to in 2. You should be able to save the .xls file as a comma delimited file. In this case the "Read for Spreadsheet File" vi should be able to just read all the data in. I'm not sure how easy it is to export an .xls file to a comma delimited format programatically.
    I think this should work all though I haven't tried it. If it doesn't then you could just read one row and then count the number of commas to determine the number of columns. You can then read the entire file and convert the data into an array, as every comma would separate each column and a carriage return would seperate each row.
    Haven't got LabVIEW on this machine so if I find anything new tomorrow I'll post again.
    Kamran

Maybe you are looking for