首先引入pom
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
寫execel 和 讀 execel 簡單的例子
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class DemoPoi {
//cell轉化任意類型
private static Object getCellValue(Cell cell) {
Object o = null;
//獲得單元格的類型
CellType cellType = cell.getCellType();
switch (cellType){
case STRING:
o=cell.getStringCellValue();//字符串數據
break;
case NUMERIC: //數字類型 , 在excel中日期類型是數字類型
//判斷是日期類型 還是數字類型
if(DateUtil.isCellDateFormatted(cell)){ //是不是日期類型
//是日期類型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
o = simpleDateFormat.format(cell.getDateCellValue());
}else{
//數字類型
o=cell.getNumericCellValue();
}
break;
case BOOLEAN:
o=cell.getBooleanCellValue();//獲得布爾類型數據
break;
default:
break;
}
return o;
}
@Test
public void ReadExecel() throws IOException {
Workbook workbook= new XSSFWorkbook("D:/demo.xlsx");
//3.獲得表
Sheet sheet = workbook.getSheetAt(0);
int rows = sheet.getLastRowNum();
/*遍歷行數*/
for (int i = 0; i < rows; i++) {
short lastCellNum = sheet.getRow(i).getLastCellNum();
for (int j = 0; j < lastCellNum ; j++) {
Cell cell = sheet.getRow(i).getCell(j);
if (cell != null) {
if (j == lastCellNum - 1) {
Object cellValue = getCellValue(cell);
System.out.println(cellValue);
} else {
Object cellValue = getCellValue(cell);
System.out.print(cellValue+" ");
}
}
}
}
}
/**
* 寫execel
* 1.有excel的對象 workBook
* 2.有sheet表
* 3.有行
* 4.有單元格(列)
* 5.賦值數據
* 6.設置樣式
* 7.下載(保存到本地)
* @param args
*/
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(1);
//row.setHeight((short) (50*20));
//設置行高
row.setHeightInPoints(50);
Cell cell = row.createCell(1);
//設置列寬
sheet.setColumnWidth(1,20*256);
cell.setCellValue("加油!大智");
//設置樣式
CellStyle cellStyle = workbook.createCellStyle();
//單元格周邊加線條
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cell.setCellStyle(cellStyle);
//設置上下,左右居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(cellStyle);
//設置字體
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 20);
//設置顏色
font.setColor((short) 3);
font.setFontName("楷體");
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
/*下載保存*/
FileOutputStream fileOutputStream = new FileOutputStream(new File("D://demo2112.xlsx"));
workbook.write(fileOutputStream);
fileOutputStream.close();
}
}
上傳和下載execel
1.上傳execel
@RequestMapping(value = "import",name = "上傳貨物")
public String importExecel(String contractId,MultipartFile file) throws IOException {
//創建貨物集合
List<ContractProduct> list =new ArrayList<ContractProduct>();
//獲取數據
if (file != null) {
//加載文件
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
Row row = null;
Cell cell = null;
for (int i = 1; i <= lastRowNum; i++) {
row = sheet.getRow(i);
short lastCellNum = row.getLastCellNum();
Object[] objects = new Object[lastCellNum];
for (int j = 0; j < lastCellNum; j++) {
cell = row.getCell(j);
if (cell != null) {
//調用上傳工具類
Object cellValue = uploadFile.getCellValue(cell);
objects[j] = cellValue;
}
}
System.out.println(Arrays.toString(objects));
//調用自定義構造
ContractProduct contractProduct = new ContractProduct(objects, user.getCompanyId(), user.getCompanyName(), contractId);
list.add(contractProduct);
//循環結束
}
contractProductService.saveList(list);
} else {
System.out.println("沒有上傳文件");
}
///WEB-INF/pages/cargo/contractProduct/import.jsp
return "redirect:/cargo/contractProduct/toImport.do?contractId="+contractId;
}
上傳重點:
//看構造
ContractProduct contractProduct = new ContractProduct(objects, user.getCompanyId(), user.getCompanyName(), contractId);
//就這
public ContractProduct(Object []objs, String companyId, String companyName,String contractId) {
this.factoryName = objs[1].toString();
this.productNo = objs[2].toString();
this.cnumber = ((Double) objs[3]).intValue();
this.packingUnit = objs[4].toString();
this.loadingRate = objs[5].toString();
this.boxNum = ((Double) objs[6]).intValue();
this.price = (Double) objs[7]; //單價
this.productRequest=objs[8].toString();
this.productDesc=objs[9].toString();
this.companyId = companyId;
this.companyName = companyName;
this.contractId = contractId;
}
1.1 上傳工具類 轉換cell各種類型爲object
//調用上傳工具類
Object cellValue = uploadFile.getCellValue(cell);
//詳情
public static Object getCellValue(Cell cell) {
Object o = null;
//獲得單元格的類型
CellType cellType = cell.getCellType();
switch (cellType){
case STRING:
o=cell.getStringCellValue();//字符串數據
break;
case NUMERIC: //數字類型 , 在excel中日期類型是數字類型
//判斷是日期類型 還是數字類型
if(DateUtil.isCellDateFormatted(cell)){ //是不是日期類型
//是日期類型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
o = simpleDateFormat.format(cell.getDateCellValue());
}else{
//數字類型
o=cell.getNumericCellValue();
}
break;
case BOOLEAN:
o=cell.getBooleanCellValue();//獲得布爾類型數據
break;
default:
break;
}
return o;
}
2.下載execel:
@RequestMapping(value = "printExcel",name = "打印出貨表")
public String printExcel(String inputDate) throws IOException {
//獲取合同數據
List<ContractProductVo> list=contractService.findByShipTime(inputDate,user.getCompanyId());
System.out.println(list);
//初始化值
Row row = null;
Cell cell = null;
//創建工作簿
Workbook workbook = new SXSSFWorkbook();
//創建表
Sheet sheet = workbook.createSheet();
//創建大標題
row = sheet.createRow(0);
//創建列
cell= row.createCell(1);
//合併單元格 從0行開始0行結束 從第一列 到 第8列結束
sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
//2019年2月 設置標題
cell.setCellValue(inputDate.replace("-","年")+"月出貨表");
//設置樣式
CellStyle cellStyle = bigTitle(workbook);
cell.setCellStyle(cellStyle);
//設置寬高
sheet.setDefaultRowHeightInPoints(36);
sheet.setDefaultRowHeight((short)(36*20));
sheet.setColumnWidth(1, 26 * 256);
sheet.setColumnWidth(2, 11 * 256);
sheet.setColumnWidth(3, 30 * 256);
sheet.setColumnWidth(4, 12 * 256);
sheet.setColumnWidth(5, 15 * 256);
sheet.setColumnWidth(6, 15 * 256);
sheet.setColumnWidth(7, 11 * 256);
sheet.setColumnWidth(8, 11 * 256);
sheet.setColumnWidth(9, 11 * 256);
//第二行 小標題 給每列賦值
Object[] objects = {"","客人", "訂單號", "貨號", "數量", "工廠", "工廠交期", "船期", "貿易條款"};
row = sheet.createRow(1);
CellStyle title = title(workbook);
for (int i = 0; i <= 8 ; i++) {
cell = row.createCell(i);
cell.setCellValue((String)objects[i]);
cell.setCellStyle(title);
}
//循環數據 遍歷輸出
for (int i = 1; i < list.size(); i++) {
//創建第三行 數據開始的第一行
row = sheet.createRow(i+1);
//獲取第一個數據對象
ContractProductVo contractProductVo = list.get(i-1);
//一行 8個單元格賦值
for (int j = 1; j <= 8 ; j++) {
cell = row.createCell(j);
switch (j) {
case 1:
cell.setCellValue(contractProductVo.getCustomName());
break;
case 2:
cell.setCellValue(contractProductVo.getContractNo());
break;
case 3:
cell.setCellValue(contractProductVo.getProductNo());
break;
case 4:
cell.setCellValue(contractProductVo.getCnumber());
break;
case 5:
cell.setCellValue(contractProductVo.getFactoryName());
break;
case 6:
cell.setCellValue(contractProductVo.getDeliveryPeriod());
break;
case 7:
cell.setCellValue(contractProductVo.getShipTime());
break;
case 8:
cell.setCellValue(contractProductVo.getTradeTerms());
break;
default:
break;
}
}
}
//文件寫回 瀏覽器
DownloadUtil downloadUtil = new DownloadUtil();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
downloadUtil.download(byteArrayOutputStream,response,"出貨表.xlsx");
return "cargo/print/contract-print";
}
下載的工具類:
package com.czh.common.utils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class DownloadUtil {
/**
* @param filePath 要下載的文件路徑
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否刪除文件
*/
protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
this.prototypeDownload(new File(filePath), returnName, response, delFlag);
}
/**
* @param file 要下載的文件
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否刪除文件
*/
protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
this.prototypeDownload(file, returnName, response, delFlag);
}
/**
* @param file 要下載的文件
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否刪除文件
*/
public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
// 下載文件
FileInputStream inputStream = null;
ServletOutputStream outputStream = null;
try {
if(!file.exists()) return;
response.reset();
//設置響應類型 PDF文件爲"application/pdf",WORD文件爲:"application/msword", EXCEL文件爲:"application/vnd.ms-excel"。
response.setContentType("application/octet-stream;charset=utf-8");
//設置響應的文件名稱,並轉換成中文編碼
//returnName = URLEncoder.encode(returnName,"UTF-8");
returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必須和頁面編碼一致,否則亂碼
//attachment作爲附件下載;inline客戶端機器有安裝匹配程序,則直接打開;注意改變配置,清除緩存,否則可能不能看到效果
response.addHeader("Content-Disposition", "attachment;filename="+returnName);
//將文件讀入響應流
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
int length = 1024;
int readLength=0;
byte buf[] = new byte[1024];
readLength = inputStream.read(buf, 0, length);
while (readLength != -1) {
outputStream.write(buf, 0, readLength);
readLength = inputStream.read(buf, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//刪除原文件
if(delFlag) {
file.delete();
}
}
}
/**
* @param byteArrayOutputStream 將文件內容寫入ByteArrayOutputStream
* @param response HttpServletResponse 寫入response
* @param returnName 返回的文件名
*/
public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
response.setContentType("application/octet-stream;charset=utf-8");
//保存的文件名,必須和頁面編碼一致,否則亂碼
returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));
System.out.println("returnName : "+returnName);
response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
response.setContentLength(byteArrayOutputStream.size());
ServletOutputStream outputstream = response.getOutputStream(); //取得輸出流
byteArrayOutputStream.writeTo(outputstream); //寫到輸出流
byteArrayOutputStream.close(); //關閉
outputstream.flush(); //刷數據
}
}
模板打印execel
@RequestMapping(value = "printExcel",name = "打印出貨表")
public String printExcel(String inputDate) throws IOException {
//獲取合同數據
List<ContractProductVo> list=contractService.findByShipTime(inputDate,user.getCompanyId());
System.out.println(list);
//初始化值
Row row = null;
Cell cell = null;
//讀取模板數據
InputStream is = session.getServletContext().getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");
//創建workbook
XSSFWorkbook workbook = new XSSFWorkbook(is);
XSSFSheet sheet = workbook.getSheetAt(0);
row = sheet.getRow(0);
cell= row.getCell(1);
//大標題
cell.setCellValue( inputDate.replace("-","年")+"月出貨表");
//小標題已寫好
//開始寫數據
//獲取樣式
row = sheet.getRow(2);
short lastCellNum = row.getLastCellNum();
//存儲每個樣式
CellStyle[] cellStyles = new CellStyle[lastCellNum];
for (int i = 1; i < lastCellNum; i++) {
cell = row.getCell(i);
CellStyle cellStyle = cell.getCellStyle();
cellStyles[i]=cellStyle;
}
//循環數據 遍歷輸出
for (int i = 1; i < list.size(); i++) {
//創建第三行 數據開始的第一行
row = sheet.createRow(i+1);
//獲取第一個數據對象
ContractProductVo contractProductVo = list.get(i-1);
//一行 8個單元格賦值
for (int j = 1; j <= 8 ; j++) {
cell = row.createCell(j);
switch (j) {
case 1:
cell.setCellValue(contractProductVo.getCustomName());
cell.setCellStyle(cellStyles[1]);
break;
case 2:
cell.setCellValue(contractProductVo.getContractNo());
cell.setCellStyle(cellStyles[2]);
break;
case 3:
cell.setCellValue(contractProductVo.getProductNo());
cell.setCellStyle(cellStyles[3]);
break;
case 4:
cell.setCellValue(contractProductVo.getCnumber());
cell.setCellStyle(cellStyles[4]);
break;
case 5:
cell.setCellValue(contractProductVo.getFactoryName());
cell.setCellStyle(cellStyles[5]);
break;
case 6:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
String format1 = simpleDateFormat1.format(contractProductVo.getDeliveryPeriod());
cell.setCellValue(format1);
cell.setCellStyle(cellStyles[6]);
break;
case 7:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(contractProductVo.getShipTime());
System.out.println(format);
cell.setCellValue(format);
cell.setCellStyle(cellStyles[7]);
break;
case 8:
cell.setCellValue(contractProductVo.getTradeTerms());
cell.setCellStyle(cellStyles[8]);
break;
default:
break;
}
}
}
//文件寫回 瀏覽器
DownloadUtil downloadUtil = new DownloadUtil();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
downloadUtil.download(byteArrayOutputStream,response,"出貨表.xlsx");
return "cargo/print/contract-print";
}
一些簡單的樣式
//大標題的樣式
public CellStyle bigTitle(Workbook wb){
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short)16);
font.setBold(true);//字體加粗
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER); //橫向居中
style.setVerticalAlignment(VerticalAlignment.CENTER); //縱向居中
return style;
}
//小標題的樣式
public CellStyle title(Workbook wb){
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontName("黑體");
font.setFontHeightInPoints((short)12);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER); //橫向居中
style.setVerticalAlignment(VerticalAlignment.CENTER); //縱向居中
style.setBorderTop(BorderStyle.THIN); //上細線
style.setBorderBottom(BorderStyle.THIN); //下細線
style.setBorderLeft(BorderStyle.THIN); //左細線
style.setBorderRight(BorderStyle.THIN); //右細線
return style;
}
//文字樣式
public CellStyle text(Workbook wb){
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontName("Times New Roman");
font.setFontHeightInPoints((short)10);
style.setFont(font);
style.setAlignment(HorizontalAlignment.LEFT); //橫向居左
style.setVerticalAlignment(VerticalAlignment.CENTER); //縱向居中
style.setBorderTop(BorderStyle.THIN); //上細線
style.setBorderBottom(BorderStyle.THIN); //下細線
style.setBorderLeft(BorderStyle.THIN); //左細線
style.setBorderRight(BorderStyle.THIN); //右細線
return style;
}
測試例子:
CellStyle cellStyle = bigTitle(workbook);
cell.setCellStyle(cellStyle);