繁体   English   中英

使用Apache POI在Java中读取/写入Excel文件时出现问题

[英]Problems Read / Write Excel File In Java Using Apache POI

大家好,我是Java Poi库的新手,我想尽我所有的运气去学习这个库,但仍然没有运气

我想要这个输出

Excel1.xls有此数据

邮政编码| 位置| 日期
211

我想复制所有第一行数据。

邮政编码| 位置| 日期

放在另一张纸上

这是我编写的代码

public static void main(String[] args) throws IOException{

    try {
        FileInputStream file = new FileInputStream(new File("d:\\input.xls"));

        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFSheet zip1 = workbook.createSheet("ZIP CODE 1");


        for(Row row : sheet){
            int i=0;

            for(Cell cell : row){

                cell.setCellType(Cell.CELL_TYPE_STRING);
                System.out.print(cell.getStringCellValue() + "\t");
                String a = cell.getStringCellValue();

                cell = zip1.createRow(i).createCell(i);

                i++;
                cell.setCellValue(a);
             }
             break;

         }

        file.close();
        FileOutputStream outFile =new FileOutputStream(new File("d:\\output.xls"));
        workbook.write(outFile);
        outFile.close();

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

发现了问题

  1. 对于.xlsx文件-> HSSFWorkbook应该是XSSFWorkbook

  2. 环。 您不想循环只希望第一行的每一行。 只是循环列

  3. 每次要写入单元格时不要创建行。 仅创建一次新行。

工作示例:

try {
    FileInputStream file = new FileInputStream(new File(
            "C:\\path\\Book1.xlsx"));

    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet sheet = workbook.getSheetAt(0);
    XSSFSheet zip1 = workbook.createSheet("ZIP CODE 1");

    Row readFirstRow = sheet.getRow(0);
    Row writeFirstRow = zip1.createRow(0);

    for (Cell cell : readFirstRow) {

        cell.setCellType(Cell.CELL_TYPE_STRING);
        String a = cell.getStringCellValue();

        cell = writeFirstRow.createCell(cell.getColumnIndex());
        cell.setCellValue(a);
    }

    file.close();
    FileOutputStream outFile = new FileOutputStream(new File(
            "C:\\path\\BookOut.xlsx"));
    workbook.write(outFile);
    outFile.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Try to use Xcelite
https://github.com/eBay/xcelite#writing

Write:

public class User { 

  @Column (name="Firstname")
  private String firstName;

  @Column (name="Lastname")
  private String lastName;

  @Column
  private long id; 

  @Column
  private Date birthDate; 
}

Xcelite xcelite = new Xcelite();    
XceliteSheet sheet = xcelite.createSheet("users");
SheetWriter<User> writer = sheet.getBeanWriter(User.class);
List<User> users = new ArrayList<User>();
// ...fill up users
writer.write(users); 
xcelite.write(new File("users_doc.xlsx"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM