2012-10-17 108 views
0

我讀的Excel文檔如下:Excel文件分隔dat文件

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

你必須做一些像HSSFRow row1 = sheet.createRow((short)0); HSSFCell cellA1 = row1.createCell((short)0); cellA1.setCellValue(「Hello」); – vels4j

回答

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(); 
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(); 
+0

我想寫入我分成分號分隔文件的行中的列。對於例如我得到的行由10列組成,那麼dat文件中的行將有10個由分號分隔的值。 – Nik

+0

好吧,從行中你可以得到cellIterator,然後通過迭代這些單元格,你可以在它們中獲取數據將這些數據添加到stringbuilder中,追加分號並且一旦完成寫入文件 – banjara