六禕-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();
        }
    }
}
























 

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