我正在阅读如下的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文件。
此外,如果列为空,则它应该作为文件中的空值,即连续分号之间没有数据。
答案 0 :(得分: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();
答案 1 :(得分: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();