zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JAVA操作Excel表格:方法二:POI的使用①:Excel实战之POI创建excel文件(低版本)

JAVAExcel文件方法 操作 实战 创建 表格
2023-09-14 09:13:43 时间

需要导入jar包:

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

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.5</version>
</dependency>

最好用maven比较方便。

注意:本文的方法只能生成和读取.xls结尾的低版本Excel文件。如果想操作高版本的Excel文件,请看我的另一篇文章。

package com.cxl;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

//使用poi创建excel文件
public class PoiExcel {
    public static void main(String[] args) {
        String[] title = {"id", "name", "sex"};
        //创建Excel工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个工作表sheet
        HSSFSheet sheet = workbook.createSheet();
        //创建第一行
        HSSFRow row = sheet.createRow(0);
        //定义cell
        HSSFCell cell = null;
        //插入第一行数据id,name,sex
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
        }
        //插入数据,从第二行开始
        for (int i = 1; i <= 10; i++) {
            HSSFRow nextrow = sheet.createRow(i);
            HSSFCell cell2 = nextrow.createCell(0);
            cell2.setCellValue("a" + i);
            cell2 = nextrow.createCell(1);
            cell2.setCellValue("user" + i);
            cell2 = nextrow.createCell(2);
            cell2.setCellValue("男");

        }
        File file = new File("f:/poi_test.xls");
        try {
            file.createNewFile();
            //将Excel内容存盘
            FileOutputStream stream = FileUtils.openOutputStream(file);
            //写入内容
            workbook.write(stream);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

结果: