2012-11-28 42 views
0

请看下面的代码。我使用JExcel API将Excel数据作为CSV获取

import java.io.*; 
import jxl.*; 
import java.util.*; 

class ConvertCSV 
{ 
    public static void main(String[] args) 
    { 
    try 
    { 
     //File to store data in form of CSV 
     File f = new File("input.csv"); 

     OutputStream os = (OutputStream)new FileOutputStream(f); 
     String encoding = "UTF8"; 
     OutputStreamWriter osw = new OutputStreamWriter(os, encoding); 
     BufferedWriter bw = new BufferedWriter(osw); 

     //Excel document to be imported 
     String filename = "C:/Users/yohan/Documents/NetBeansProjects/ExcelTest/input.xlsx"; 
     WorkbookSettings ws = new WorkbookSettings(); 
     ws.setLocale(new Locale("en", "EN")); 
     Workbook w = Workbook.getWorkbook(new File(filename),ws); 

     // Gets the sheets from workbook 
     for (int sheet = 0; sheet < w.getNumberOfSheets(); sheet++) 
     { 
     Sheet s = w.getSheet(sheet); 

     bw.write(s.getName()); 
     bw.newLine(); 

     Cell[] row = null; 

     // Gets the cells from sheet 
     for (int i = 0 ; i < s.getRows() ; i++) 
     { 
      row = s.getRow(i); 

      if (row.length > 0) 
      { 
      bw.write(row[0].getContents()); 
      for (int j = 1; j < row.length; j++) 
      { 
       bw.write(','); 
       bw.write(row[j].getContents()); 
      } 
      } 
      bw.newLine(); 
     } 
     } 
     bw.flush(); 
     bw.close(); 
    } 
    catch (UnsupportedEncodingException e) 
    { 
     System.err.println(e.toString()); 
    } 
    catch (IOException e) 
    { 
     System.err.println(e.toString()); 
    } 
    catch (Exception e) 
    { 
     System.err.println(e.toString()); 
    } 
    } 
} 

我不想将数据写入到一个CSV文件,但我MUST负载“字段”到StringBuffer称为“filedsBuffer”和数据加载到一个StringBuffer叫“的DataBuffer”为逗号分隔值。

但是,当我运行此程序时,出现以下异常。

jxl.read.biff.BiffException: Unable to recognize OLE stream 

我该如何解决这个问题?如果我无法通过此API执行此操作,请随时使用其他API进行回答。请帮助

+0

您可以测试将文件扩展名更改为.xls而不是.xlsx。它可能会帮助你。 –

+0

jxl是否支持xlsx格式 - 许多问题和答案都表明jxl支持旧格式而不是xlsx? – Jayan

+0

@Jayan:是的,可能是..为什么我更新它,如果可能的话要求不同的API –

回答

2

您可以考虑使用apache-poi。它支持最新版本的ms-excel。这里的代码可以帮助get started -

+0

就可以了。谢谢......... –