0

我正在阅读如下的excel文档:

package com.sample.file;

//necessary imports goes here

public class ExcelReader { 
   public static void main(String[] args) throws Exception{ 

  String fname = "C:\\myExcel.xls"; // or  "C:\\myExcel.xlsx"  
  InputStream inp = new FileInputStream(fname); 
  Workbook wb = WorkbookFactory.create(inp); 
  Sheet sheet = null; 

  sheet = wb.getSheetAt(0); 

  Iterator rows = sheet.rowIterator(); 

  while (rows.hasNext()) 
    { 
            Row row = (Row) rows.next(); 

            // how to write to a semicolon delimited dat file here
    }

  inp.close(); 
} 
}

如上所示,我能够读取该行。但是,现在我想将该行写入分号分隔的 dat 文件中。

此外,如果一列是空的,它应该在文件中作为一个空值,即连续分号之间没有数据。

4

2 回答 2

1
final StringBuilder sb = new StringBuilder("");
while (rows.hasNext()) {
    Row row = (Row) rows.next(); 
    // how to write to a semicolon delimited dat file here
    Iterator<Cell> cells = row.cellIterator();

     while (cells.hasNext()) {
        Cell cell = cells.next();
        sb.append(cell.toString()).append(";");
    }
    sb.append("\n");
}   

File file = new File("someFile.dat");

if (!file.exists()) {
    file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(sb.toString());
bw.close();
于 2012-10-17T05:21:49.260 回答
0

假设“row.toString”返回一些字符串添加“row.toString”到stringbuilder,分号分隔

然后在你的while循环之后

            File file = new File("filename.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content.toString); //content is your stringbuilder
            bw.close();
于 2012-10-17T05:06:35.393 回答