六祎-POI创建Excel文件之高版本2017版以上(IDEA版本)

第一步:导入所需的jar包

第二步:上代码




import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


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

/**
 * 使用POI创建Excel(2017版以上)
 */
public class POICJ {
    public static void main(String[] args) {
        //创建一个数组,存放数据
        String[] title = {"id","name","sex"};

        //创建excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();

        //创建一个工作表sheet
        Sheet sheet = workbook.createSheet();
        //创建第一行,从0开始
        Row row = sheet.createRow(0);
        //定义cell
        Cell 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++){
            Row nextrow =sheet.createRow(i);
            Cell 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("d:/poi_xlh_test.xlsx");
        try {
            file.createNewFile();
            //将excel内容存盘
            FileOutputStream stream = FileUtils.openOutputStream(file);
            workbook.write(stream);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
























 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章