1、什麼是POI?
Apache POI 是 Apache 軟件基金會的開放源碼函式庫,POI 提供 API 給 Java 程序對
Microsoft Office 格式檔案讀和寫的功能。
常用的兩種java操作Excel技術POi和JXL的對比:
POI 和 JXL 對 Excel 抽象出來的對象對比
POI | JXL | |
---|---|---|
Excel 文檔 | HSSFWorkbook | Workbook |
Excel 的工作表 | HSSFSheet | Sheet |
Excel 的行 | HSSFRow | 無 |
Excel 中的單元格 | HSSFCell | Cell |
Excel 字體 | HSSFFont | |
Excel 單元格樣式 | HSSFCellStyle | |
Excel 顏色 | HSSFColor | |
合併單元格 | CellRangeAddress |
2、使用POI實現Excel的導入導出
先來回憶一下window使用Excel和POi對Excel抽象出來的對象
- 創建一個Excel文件 HSSFWorkbook
- 創建一張工作表 HSSFSheet
- 選中一行 HSSFRow
- 選中一個單元格 HSSFCell
- 在單元格中寫入數據
- 保存
第一個demo Excel導出
1,導入POI依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
2,POI工具類實現導出
案例1:
package com.macw;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class PoiTest {
@Test
public void test1() throws IOException {
// 1.創建一個文件對象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
// 2.創建一個表對象 通過文件對象創建表對象
HSSFSheet sheet = hssfWorkbook.createSheet("表名:excel數據表");
// 3.獲取行對象 下標從0開始
HSSFRow row = sheet.createRow(0);
// 4.獲取第1個單元格 下標從0開始
HSSFCell cell = row.createCell(0);
// 5.在單元格中寫入數據
cell.setCellValue("Hello Wolld");
// 6.保存在磁盤中 流 文件名的後綴必須有.xls
hssfWorkbook.write(new FileOutputStream("E://demo.xls"));
}
}
```java
案例2:
模擬從數據庫查到的所有用戶及用戶信息導出到excel文件中
@RequestMapping("/exportAll")
public void exportAll(HttpServletResponse resp){
//模擬從數據庫查到的所有用戶及用戶信息
List<User> users = new ArrayList<User>();
User user = new User("1","張三 1","2019-8-10");
User user1 = new User("2","張三 2","2019-8-10");
User user2 = new User("3","張三 3","2019-8-10");
User user3 = new User("4","張三 4","2019-8-10");
User user4 = new User("5","張三 5","2019-8-10");
User user5 = new User("6","張三 6","2019-8-10");
User user6 = new User("7","張三 7","2019-8-10");
User user7 = new User("8","張三 8","2019-8-10");
users.add(user);
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
users.add(user6);
users.add(user7);
//創建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//創建工作表
HSSFSheet sheet = workbook.createSheet("用戶信息");
//設置列寬 第一個參數:列索引 第二個參數:列寬
sheet.setColumnWidth(2, 4500);
//創建導出樣式
HSSFCellStyle cellStyle = workbook.createCellStyle();
//創建字體
HSSFFont font = workbook.createFont();
//設置字體顏色
font.setColor(HSSFFont.COLOR_RED);
//設置加粗
font.setBold(true);
//設置字體
font.setFontName("宋體");
//設置居中
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
//管理字體樣式
cellStyle.setFont(font);
//創建標題欄
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
String[] titles = {"編號","真實姓名","出生年月"};
for (int i = 0; i < titles.length; i++) {
cell = row.createCell(i);
cell.setCellValue(titles[i]);
//標題行使用樣式
cell.setCellStyle(cellStyle);
}
for (int i = 1; i <= users.size(); i++) {
//創建數據行對象
row = sheet.createRow(i);
//數據行第一列設值
cell = row.createCell(0);
cell.setCellValue(users.get(i-1).getUserId());
//數據行第二列設值
cell = row.createCell(1);
cell.setCellValue(users.get(i-1).getRealname());
//數據行第三列設值
cell = row.createCell(2);
cell.setCellValue(users.get(i-1).getDharmaName());
}
String fileName = "用戶報表("+new
SimpleDateFormat("yyyy-MM-dd").format(new Date())+").xls";
//處理中文下載名亂碼
try {
fileName = new String(fileName.getBytes("utf-8"),"utf-8");
//設置 response
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("content-disposition","attachment;filename="+fileN
ame);
workbook.write(resp.getOutputStream());
workbook.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3、POI導入
@RequestMapping("/uploadIn")
@ResponseBody
public Map uploadIn(MultipartFile multipartFile) throws IOException {
//輸出文件名
logger.info("----------文件名爲: "+multipartFile.getOriginalFilename());
//1,獲取流對象
InputStream inputStream = multipartFile.getInputStream();
// 2.通過poi解析流 得到 Excel文件對象
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
// 3.通過對象獲取數據 得到表
HSSFSheet sheet = workbook.getSheetAt(0);
// 4.通過表 得到行
int lastRowNum = sheet.getLastRowNum();
//定義計數器,計算批量導入多少條數據
int sum = 0;
for (int i = 1; i <= lastRowNum; i++) {
Guru guru = new Guru();
HSSFRow row = sheet.getRow(i);
// 獲取單元格
double guruId = row.getCell(0).getNumericCellValue();
guru.setGuruId((int) guruId);
guru.setGuruName(row.getCell(1).getStringCellValue());
guru.setGuruImage(row.getCell(2).getStringCellValue());
guru.setGuruNickname(row.getCell(3).getStringCellValue());
guru.setGuruStatus((int) row.getCell(4).getNumericCellValue());
System.out.println(guru);
//執行添加的SQL
int insert = guruMapper.insert(guru);
//統計添加成功的條數
sum+=insert;
}
Map map = new HashMap();
map.put("flag", sum+"");
return map;
}
頁面代碼:
<div id="insertFile" class="easyui-dialog" data-options="closed:true">
<form id="insertFileForm" enctype="multipart/form-data" method="post">
上傳Excel文件:<input class="easyui-filebox" name="multipartFile"
data-options="required:true,missingMessage:'請選擇文件'"/><br/><br/>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-save" onClick="insertFileConfirm()">上傳</a>
</form>
</div>
js代碼:
//批量上傳的文件提交
function insertFileConfirm() {
$("#insertFileForm").form("submit", {
url: "${pageContext.request.contextPath}/guru/uploadIn",
success: function (data) {
console.log(data);
alert("成功添加:"+data.flag+" 條數據");
$("#insertFile").dialog("close");
$("#guruManager").datagrid("reload");
}
})
}