欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java导入导出Excel

程序员文章站 2024-02-24 13:31:52
...

pom.xml

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>

实例

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
...
HSSFWorkbook workbook = new HSSFWorkbook(); // 工作表
HSSFSheet sheet = workbook.createSheet();   // 表页
HSSFRow row = sheet.createRow(0);           // 单元行

row.createCell(0).setCellValue("编号");
row.createCell(1).setCellValue("产品名称");
row.createCell(2).setCellValue("星级");
row.createCell(3).setCellValue("单价");
row.createCell(4).setCellValue("图片");
row.createCell(5).setCellValue("所属类别");
row.createCell(6).setCellValue("类别排名");

for (int i = 0; i < infos.size(); i++) {
    ProductInfo info = infos.get(i);
    row = sheet.createRow(i + 1);
    row.createCell(0).setCellValue("No." + i);
    row.createCell(1).setCellValue(info.getName());
    row.createCell(2).setCellValue(info.getStar());
    row.createCell(3).setCellValue(info.getPrice());
    row.createCell(4).setCellValue(info.getImage());
    row.createCell(5).setCellValue(info.getType());
    row.createCell(6).setCellValue(info.getRanking());
}

try {
    FileOutputStream fos = new 
    FileOutputStream("/Users/vincent/Desktop/Test.xls");
    workbook.write(fos);
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}