POI按照模版導出Excel數據

POI按照模版導出Excel數據

一、所需jar包

二、ExportExcelUtil.java

package com.upsoft.exportexcel;



import java.io.FileInputStream;

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class ExportExcelUtil {



public static void main(String[] args) throws Exception {



ExportExcelUtil export = new ExportExcelUtil();

String srcFilePath = "d:/人員信息模板.xlsx";

String fileName = "test_" + System.currentTimeMillis() + ".xlsx";

String desFilePath = "d:/" + fileName;



export.exportExcel(srcFilePath,desFilePath);

}



//根據指定的excel模板導出數據

public void exportExcel(String srcFilePath,String desFilePath) throws Exception {



//創建Excel文件的輸入流對象

FileInputStream fis = new FileInputStream(srcFilePath);

//根據模板創建excel工作簿

XSSFWorkbook workBook = new XSSFWorkbook(fis);

//創建Excel文件輸出流對象

FileOutputStream fos = new FileOutputStream(desFilePath);

//獲取創建的工作簿第一頁

XSSFSheet sheet = workBook.getSheetAt(0);

//給指定的sheet命名

workBook.setSheetName(0,"2016-11-30"); 



//修改標題

XSSFRow row = sheet.getRow(0);

XSSFCell cell = row.getCell(0);

//獲取指定單元格值

String s = cell.getStringCellValue();

cell.setCellValue("修改後的標題爲:"+s);



//獲取當前sheet最後一行數據對應的行索引

int currentLastRowIndex = sheet.getLastRowNum();

int newRowIndex = currentLastRowIndex + 1;

XSSFRow newRow = sheet.createRow(newRowIndex);

//開始創建並設置該行每一單元格的信息,該行單元格的索引從 0 開始

int cellIndex = 0;



//創建一個單元格,設置其內的數據格式爲字符串,並填充內容,其餘單元格類同

XSSFCell newNameCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_STRING);

newNameCell.setCellValue("喬玉寶");

XSSFCell newGenderCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_STRING);

newGenderCell.setCellValue("男");

XSSFCell newAgeCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_NUMERIC);

newAgeCell.setCellValue(25);

XSSFCell newAddressCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_NUMERIC);

newAddressCell.setCellValue("重慶市渝北區");



workBook.write(fos);



//關閉流

fis.close();

fos.flush();

fos.close();

System.out.println("導出成功");

}

}

三、結果

1、模版Excel

 

 

2、導出數據後的Excel

 

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