2017-12-18 186 views
0

我想通过网络表格将数据写入excel。
开始的行使用空白数据创建,最后一行填充数据,最后一个索引值。
即使数据存在于Arraylist中,其他行也没有被填充数据。只有最后一个索引值被插入到Excel表格

public class Write_Excel {  
    public static `FileInputStream` `fis`;  
    public static FileOutputStream fos;  
    public static `HSSFWorkbook` `wb`;  
    public static `HSSFSheet` `sheet`;  
    public static `HSSFCell` `cell`; 
    public static `HSSFRow` `row`; 
    public static `int a = 0`; 

public static void write_Excel(String fileName, String sheetName, 
      `ArrayList`<String> `dataToWrite`) throws `IOException` { 
    fos = new `FileOutputStream(fileName); 
    wb = new HSSFWorkbook(); 
    sheet = `wb.createSheet(sheetName);` 
    `row = sheet.createRow(a++);` 
    for (int i = 0; i < 16; i++) { 
     cell = row.createCell(i); 
     System.out.println(dataToWrite.get(i).toString()); 
     cell.setCellValue(new HSSFRichTextString(dataToWrite.get(i))); 
     } 
    wb.write(fos); 
    fos.flush(); 
    } 
} 
+0

你只有一个要写的字符串列表,你想要每行1个字符串,还是全部在同一行?或者每次调用该方法时在数据中添加一行? – Bentaye

+0

每次拨打方法 –

+0

时我都会添加一行新数据,我在下面添加了一个答案。 – Bentaye

回答

0

当你这样做,你需要创建一个新的工作簿每次调用的函数,你刚刚结束抹去以前的。因此你只能得到最后一次通话的结果。

如果您想在每次调用时添加一行,请按照这种方式进行,您需要将行号和工作簿作为类变量。此外,您需要掌握已经创建的工作表以追加到工作表。或者你也会抹去它。

public static void main(String[] args) { 
    try { 

     write_Excel("myFile.xls","sheetName", 
      Arrays.asList("value 1", "value 2", "value 3")); 

     write_Excel("myFile.xls","sheetName", 
      Arrays.asList("value 4", "value 5", "value 6")); 

    } catch(IOException e) { 
     e.printStackTrace(); 
    } 
    } 

    private static int newRowIndex = 0; 
    private static HSSFWorkbook workbook = new HSSFWorkbook(); 

    public static void write_Excel(String fileName, String sheetName, List<String> dataToWrite) throws IOException { 
    FileOutputStream fos = new FileOutputStream(fileName); 

    // open or create sheet 
    HSSFSheet sheet = workbook.getSheet(sheetName) != null ? 
     workbook.getSheet(sheetName) : 
     workbook.createSheet(sheetName); 

    // create a new row 
    HSSFRow row = sheet.createRow(newRowIndex ++); 

    // write your data in the new row 
    for (int colIndex = 0; colIndex < dataToWrite.size(); colIndex++) { 
     HSSFCell cell = row.createCell(colIndex); 
     cell.setCellValue(new HSSFRichTextString(dataToWrite.get(colIndex))); 
    } 

    workbook.write(fos); 
    fos.flush(); 
    fos.close(); 
    } 
+0

我用这个代码的引用仍然是最后一个索引值插入到excel –

+0

我测试了这个代码,它在xls文件中写了2行。 – Bentaye

+0

在这种情况下,2行被创建,但第1行是空白的。 –

1

你应该加入这一行成环

HSSFRow row = sheet.createRow(a++);