将Excel数据作为CSV格式

时间:2012-11-28 04:43:46

标签: java excel csv io jexcelapi

请查看以下代码。我正在使用JExcel API

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文件,但我必须将'Fields'加载到名为“filedsBuffer”的StringBuffer中,并将数据加载到名为“dataBuffer”的StringBuffer中作为逗号分隔值

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

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

我该如何解决这个问题?如果我不能使用此API执行此操作,请随时使用其他API进行回答。请帮忙

1 个答案:

答案 0 :(得分:2)

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