尝试提取数据并写入另一个电子表格时出现空

时间:2015-10-08 14:50:29

标签: java excel apache-poi

创建了输出文件,但只写入了第一个单元格而没有其他单元格。我用系统打印测试了它,我想要的所有数据都显示在控制台中,但没有写入工作表。

public class excel_read_2 {

public static void main(String[] args) 
{
    try
    {
        FileInputStream file = new FileInputStream(new File("C:/Users/h.M/Desktop/20151007-110016_outgoing.xls")); //input
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheetAt(0);           

        Workbook wb = new HSSFWorkbook();
        Sheet sheet1 = wb.createSheet("new sheet");
        FileOutputStream fileOut = new FileOutputStream("C:/Users/h.M/Desktop/workbook.xls");  //output

        int rowcounter = 0;
        for (int rowNum = 150; rowNum < 180; rowNum++) {
            Row r = sheet.getRow(rowNum); 
            if (r == null) {
                continue;
            }
            int lastColumn=6;
            for (int cn = 0; cn < lastColumn; cn++) {
                Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
                if (c == null){
                }           
                else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {                
                    Row row = sheet1.createRow((short)rowcounter);
                    Cell cell = row.createCell(cn);
                    row.createCell(cn).setCellValue(c.getStringCellValue());

                    System.out.println("The cell was a string \" " + c.getStringCellValue()+" \" ");

                } else if (c.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                    Row row = sheet1.createRow((short)rowcounter);
                    Cell cell = row.createCell(cn);
                    row.createCell(cn).setCellValue(c.getNumericCellValue());

                    System.out.println("The cell was a number " + c.getNumericCellValue());
                }
            }
            rowcounter++;           
        } 
                    wb.write(fileOut);
        fileOut.close();
        file.close();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
  }
}

1 个答案:

答案 0 :(得分:1)

在循环之前创建新行,然后在每个循环中使用一次。

                Row row = sheet1.createRow((short)rowcounter);
                int lastColumn=6;
                for (int cn = 0; cn < lastColumn; cn++) {
                    Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
                    if (c == null){
                    }           
                    else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        Cell cell = row.createCell(cn);
                        cell.setCellValue(c.getStringCellValue());