在項目中,有很多對excel的操作,大都數時候我們都會使用poi工具類,本文将介紹poi的一些使用方法。
1.poi導入excel,并展示資料
使用poi導入excel,解析後傳回List資料到前台展示。
/**
*
* (讀入excel檔案,解析後傳回)
* @param file(檔案類型)
* @throws IOException
* @return List<String[]>
*/
public static List<String[]> readExcel(MultipartFile file)
throws IOException {
// 檢查檔案
checkFile(file);
// 獲得Workbook工作薄對象
Workbook workbook = getWorkBook(file);
// 建立傳回對象,把每行中的值作為一個數組,所有行作為一個集合傳回
List<String[]> list = new ArrayList<String[]>();
if (workbook != null) {
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++ ) {
// 獲得目前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if (sheet == null) {
continue;
}
// 獲得目前sheet的開始行
int firstRowNum = sheet.getFirstRowNum();
// 獲得目前sheet的結束行
int lastRowNum = sheet.getLastRowNum();
// 循環除了第一行的所有行
for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++ ) {
// 獲得目前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
// 獲得目前行的開始列
int firstCellNum = row.getFirstCellNum();
// 獲得目前行的列數
int lastCellNum = row.getLastCellNum();
String[] cells = new String[row.getLastCellNum()];
// 循環目前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++ ) {
Cell cell=row.getCell(cellNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}
/**
*
* (判斷檔案)
* @param file
* @throws IOException
* @return void
*/
public static void checkFile(MultipartFile file)
throws IOException {
// 判斷檔案是否存在
if (null == file) {
throw new FileNotFoundException("檔案不存在!");
}
// 獲得檔案名
String fileName = file.getOriginalFilename();
// 判斷檔案是否是excel檔案
if (!fileName.endsWith(XLS_TYPE) && !fileName.endsWith(XLSX_TYPE)) {
throw new IOException(fileName + "不是excel檔案");
}
}
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 把數字當成String來讀,避免出現1讀成1.0的情況
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cell.setCellType(Cell.CELL_TYPE_STRING);
}
// 判斷資料的類型
switch (cell.getCellType()) {
// 數字
case Cell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
// 字元串
case Cell.CELL_TYPE_STRING:
cellValue = String.valueOf(cell.getStringCellValue());
break;
// Boolean
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
// 公式
case Cell.CELL_TYPE_FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
// 空值
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
// 故障
case Cell.CELL_TYPE_ERROR:
cellValue = "非法字元";
break;
default:
cellValue = "未知類型";
break;
}
return cellValue;
}
/**
*
* (getWorkBook:(建立WorkBook對象))
* @param file
* @return
* @return Workbook
*/
public static Workbook getWorkBook(MultipartFile file) {
// 獲得檔案名
String fileName = file.getOriginalFilename();
// 建立Workbook工作薄對象,表示整個excel
Workbook workbook = null;
try {
// 擷取excel檔案的io流
InputStream is = file.getInputStream();
// 根據檔案字尾名不同(xls和xlsx)獲得不同的Workbook實作類對象
if (fileName.endsWith(XLS_TYPE)) {
// 2003
workbook = new HSSFWorkbook(is);
}
else if (fileName.endsWith(XLSX_TYPE)) {
// 2007
workbook = new XSSFWorkbook(is);
}
}
catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
2.poi導出excel并以web下載下傳方式儲存excel
将資料庫中的資料組裝成excel并導出,并在web下載下傳欄中直接下載下傳。
/**
* 人員導出
*
* @param sysSysUserVO
* @throws IOException
*/
@PostMapping("/exportUser")
@ApiOperation(value = "導出人員excel", notes = "導出人員excel")
public void
exportUser(@ApiParam(name = "人員id", value = "人員id", required = false) @RequestBody List<SysUserVO> sysSysUserVO)
throws IOException {
List<SysUserVO> middleList = new ArrayList<>();
// 查詢使用者詳細資訊
for (SysUserVO sysUserVO : sysSysUserVO) {
List<SysUserVO> resultListSysUser = sysUserService.querySysUserAll(sysUserVO);
userInfoUtil.completionInformation(resultListSysUser.get(0));
middleList.add(resultListSysUser.get(0));
}
// excle格式
String[] headers = {"使用者名", "姓名", "密碼", "啟動狀态", "崗位", "角色", "所屬部門", "手機", "郵箱", "身份證号"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
// 設定列寬
sheet.setDefaultColumnWidth((short)18);
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
// 建立單元格,每行多少資料就建立多少個單元格
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
// 給單元格設定内容
cell.setCellValue(text);
}
for (int j = 0; j < middleList.size(); j++) {
SysUserVO export = middleList.get(j);
// 從第二行開始填充資料
row = sheet.createRow(j + 1);
List<String> datas = new ArrayList<>();
String userName = export.getUsername();
String trueName = export.getTureName();
String password = export.getPassword();
String status = String.valueOf(export.getIsEnabled());
String postName = export.getPostName();
String roleName = export.getRoleName();
String organName = export.getOrganizationName();
String phone = export.getMobile();
String email = export.getEmail();
String identityCard = export.getIdentityCard();
datas.add(userName);
datas.add(trueName);
datas.add(password);
datas.add(status);
datas.add(postName);
datas.add(roleName);
datas.add(organName);
datas.add(phone);
datas.add(email);
datas.add(identityCard);
for (int k = 0; k < datas.size(); k++) {
String string = datas.get(k);
HSSFCell cell = row.createCell(k);
HSSFRichTextString richString = new HSSFRichTextString(string);
HSSFFont font3 = workbook.createFont();
// 定義Excel資料顔色,這裡設定為藍色
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
String fileName = "人員導出.xls";
// 導出
HttpServletResponse response =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
RequestAttributes requsetAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes)requsetAttributes).getRequest();
// 獲得浏覽器代理資訊
final String userAgent = request.getHeader("USER-AGENT");
// 判斷浏覽器代理并分别設定響應給浏覽器的編碼格式
if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
// IE浏覽器
fileName = URLEncoder.encode(fileName, "UTF-8");
} else if (StringUtils.contains(userAgent, "Mozilla")) {
// google,火狐浏覽器
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
} else {
// 其他浏覽器
fileName = URLEncoder.encode(fileName, "UTF-8");// 其他浏覽器
}
// 設定HTTP響應頭
response.reset();
// 重置 如果不在頁面上顯示而是下載下傳下來 則放開注釋
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
OutputStream os = response.getOutputStream();
workbook.write(os);
os.close();
}
3.poi導出并以流方式儲存excel
将資料庫中的資料組裝成excel并導出,并以資料流方式存在指定的路徑。
public class BarcodeExportlFlow implements IBarcodeExport {
@Autowired
BarcodeManageBatchSerivce barcodeManageBatchSerivce;
@Override
public OutputStream exportData() throws IOException {
//查詢批次碼
BarcodeBatchManageBo input = new BarcodeBatchManageBo();
List<BarcodeBatchManageBo> middleList = barcodeManageBatchSerivce.selectBatch(input);
String[] headers = {"id", "條碼批次碼", "激活狀态", "有效狀态", "導入人", "導入時間", "激活人", "激活時間", "廢棄人", "廢棄時間", "本批次條數"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
//設定列寬
sheet.setDefaultColumnWidth((short) 18);
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
//建立單元格,每行多少資料就建立多少個單元格
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
//給單元格設定内容
cell.setCellValue(text);
}
for (int j = 0; j < middleList.size(); j++) {
BarcodeBatchManageBo export = middleList.get(j);
//從第二行開始填充資料
row = sheet.createRow(j + 1);
List<String> datas = new ArrayList<>();
String id = export.getId().toString();
String batchCode = export.getBatchCode();
String activationStatus = export.getActivationStatus();
String effectiveStatus = export.getEffectiveStatus();
datas.add(id);
datas.add(batchCode);
datas.add(activationStatus);
datas.add(effectiveStatus);
for (int k = 0; k < datas.size(); k++) {
String string = datas.get(k);
HSSFCell cell = row.createCell(k);
HSSFRichTextString richString = new HSSFRichTextString(string);
HSSFFont font3 = workbook.createFont();
//定義Excel資料顔色,這裡設定為藍色
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
FileOutputStream fos = new FileOutputStream("D:/wb.xls");
workbook.write(fos);
fos.close();
return null;
}
}