对excel的完美操作

对excel的完美操作

package com.dxm.ide.util;

import org.apache.commons.io.FileUtils;
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.util.Date;
import java.util.List;

public class CreateExcel {


    //生成excel
    public static String create(List datas, String path) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("数据表一");
        sheet.setDefaultColumnWidth(20);

        //新增数据行,并且设置单元格数据
        int rowNum = 0;
        for (String i : datas) {

            HSSFRow row = sheet.createRow(rowNum);
            String[] splits = i.split("\t");
            int m = 0;
            for (String j : splits) {
                row.createCell(m).setCellValue(j);
                m++;

            }
            rowNum++;
        }

        //生成excel文件
        return buildExcelFile(path, workbook);


    }

    //生成excel文件
    protected static String buildExcelFile(String path, HSSFWorkbook workbook) throws Exception {
        File file = new File(path + new Date().getTime() + ".xlsx");
        file.createNewFile();
        //将excel写入
        FileOutputStream fos = FileUtils.openOutputStream(file);
        workbook.write(fos);
        fos.flush();
        fos.close();

        return file.getAbsolutePath();
    }


}

你可能感兴趣的:(极简方案)