简体   繁体   English

使用 Java 和 Jexcelapi 从 Excel 写入多个 CSV 文件

[英]Writing Multiple CSV Files From Excel using Java and Jexcelapi

I'm trying to create a program that writes all the data from excel to multiple csv files.我正在尝试创建一个程序,将所有数据从 excel 写入多个 csv 文件。

Currently, my program creates n number of files, and only the last row of excel is being written on the last csv file.目前,我的程序创建了n个文件,并且只有最后一行 excel 正在写入最后一个 csv 文件。

Programming Background Observation:编程背景观察:

It seems like the file is writing.好像文件正在写入。 But for each written row, it somehow creates the same file 250 times.但是对于每个写入的行,它会以某种方式创建相同的文件 250 次。 It erases the row that was written last.它擦除最后写入的行。

I may have some problems using the OutputStream or BufferedWriter .我在使用OutputStreamBufferedWriter 时可能会遇到一些问题。 I just can't figure out what it is.我只是想不通它是什么。

writeRow() method: writeRow() 方法:

public static void writeRow(BufferedWriter bw, Cell[] row) throws IOException { 
    if (row.length > 0) {
        bw.write(row[0].getContents());
        for (int j = 1; j < row.length; j++) {
            bw.write(',');
            bw.write(row[j].getContents());
        }
    }
}

setFile() method: setFile() 方法:

public static BufferedWriter setFile (int i) throws IOException {
    i=i/250;
    File f = new File(dir + "file-" + (i+1) + ".csv");
    // If i has changed, create a new file. Else, append to current file.
    String encoding = "UTF8";
    OutputStream os = null;
    OutputStreamWriter osw = null;
    BufferedWriter bw = null;
    Boolean append = null;
    try {
        // If i has changed, create a new file, else append.
        if (i%250==0) {
            append = new Boolean("TRUE");
            os = new FileOutputStream(f,append);
        } else {
            append = new Boolean("FALSE");
            os = new FileOutputStream(f, append);
        }
        osw = new OutputStreamWriter(os, encoding);
        bw = new BufferedWriter(osw);

    } finally {
        os.close();
        osw.close();
    }
    return bw;
}

Here are the exceptions.以下是例外情况。

Exception in thread "main" java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at Main.main(Main.java:46)

Below are some of the links to the code.下面是代码的一些链接。

What am I doing wrong?我究竟做错了什么?

Here is the svn trunk:这是 svn 主干:

https://franz-opensource.googlecode.com/svn/trunk/ExcelToCsv -https://franz-opensource.googlecode.com/svn/trunk/ExcelToCsv -

Important Advice: Instead of writing on the same buffer, stop the rows, after every nth records.重要建议:不要在同一个缓冲区上写入,而是在每第 n条记录之后停止行。 Then, read the worksheet again.然后,再次阅读工作表。 Then, output buffer on another file.然后,在另一个文件上输出缓冲区。 You can not be able to change the file while writing on the same buffer.在同一缓冲区上写入时,您无法更改文件。

Here is the whole solution piece by piece:这是一个一个的整个解决方案:

Static variables:静态变量:

public static int maxRecords = 250;
public static String directory = "C:\\Users\\User02\\workspace\\ExcelToCsv\\src\\";
public static String inputFile = directory + "inventory.xls";

Main:主要的:

public static void main(String[] args) throws BiffException, IOException {
Sheet s = getSheet();
    int countRows = s.getRows(); // counts the number of rows in the sheet.
    int numberOfFiles = (countRows/maxRecords)+1;

    for(int file=0; file<numberOfFiles; file++) {
        System.out.println("Create file number " + (file+1));
        int fileNumber = file+1;
        System.out.println("Start number: " + ((file*maxRecords)+1));
        int startNumber = (file*maxRecords);
        populateFile(fileNumber,startNumber);
        System.out.println("");
    }
}

Populate List:填充列表:

public static void populateFile(int fileNumber, int startNumber) 
    throws IOException, BiffException {
        BufferedWriter bw = setFile(fileNumber);
        Sheet s = getSheet();
        Cell[] row = null;
        writeRow(bw,s.getRow(0));
        bw.newLine(); 
        int limit = getLimit(s,startNumber);
        System.out.println("End Number:" + limit);
        System.out.println();
        for (int i = startNumber; i < limit ; i++) {
            row = s.getRow(i); 
            //System.out.println(i);
            writeRow(bw,row);
            bw.newLine();
        }
        bw.flush();
        bw.close();
    }

Get the Sheet:获取表:

public static Sheet getSheet() throws BiffException, IOException {
    WorkbookSettings ws = new WorkbookSettings();
    ws.setLocale(new Locale("en", "EN"));
    Workbook w = Workbook.getWorkbook(new File(inputFile),ws);
    Sheet s = w.getSheet(0);
    return s;
}

Setting the File to write to:设置要写入的文件:

public static BufferedWriter setFile(int fileNumber) throws IOException {
    String csvFilename = directory + "file-"+ fileNumber +".csv";
    FileWriter csvFile = new FileWriter(csvFilename);
    BufferedWriter bw = new BufferedWriter(csvFile);
    return bw;
}

Getting the Limit:获得极限:

public static int getLimit(Sheet s, int startNumber) {
    int limit;
    int countRows = s.getRows();
    if (startNumber+maxRecords<=countRows) {
        limit = startNumber + maxRecords;
    } else {
        limit = startNumber + (countRows-startNumber);
    }
    return limit;
}

Write the Rows to file:将行写入文件:

public static void writeRow(BufferedWriter bw, Cell[] row) throws IOException { 
    if (row.length > 0) {
        bw.write(row[0].getContents());
        for (int j = 1; j < row.length; j++) {
            bw.write(',');
            bw.write(row[j].getContents());
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM