java批量導(dǎo)入導(dǎo)出文件的實(shí)例分享(兼容xls,xlsx)
一、介紹
利用java實(shí)現(xiàn)文件的導(dǎo)入導(dǎo)出數(shù)據(jù)庫(kù),目前在大部分系統(tǒng)中是比較常見(jiàn)的功能了,今天寫(xiě)個(gè)小demo來(lái)理解其原理,沒(méi)接觸過(guò)的同學(xué)也可以看看參考下。
目前我所接觸過(guò)的導(dǎo)入導(dǎo)出技術(shù)主要有POI和iReport,poi主要作為一些數(shù)據(jù)批量導(dǎo)入數(shù)據(jù)庫(kù),iReport做報(bào)表導(dǎo)出。另外還有jxl類(lèi)似poi的方式,不過(guò)貌似很久沒(méi)跟新了,2007之后的office好像也不支持,這里就不說(shuō)了。
二、POI使用詳解
2.1 什么是Apache POI?
Apache POI是Apache軟件基金會(huì)的開(kāi)放源碼函式庫(kù),POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫(xiě)的功能。
2.2 POI的jar包導(dǎo)入
本次講解使用maven工程,jar包版本使用poi-3.14和poi-ooxml-3.14。目前最新的版本是3.16。因?yàn)?.15以后相關(guān)api有更新,部分操作可能不一樣,大家注意下。
<!-- poi的包 3.15版本后單元格類(lèi)型獲取方式有調(diào)整 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency>
2.3 POI的API講解
2.3.1 結(jié)構(gòu)
- HSSF - 提供讀寫(xiě)Microsoft Excel格式檔案的功能。
- XSSF - 提供讀寫(xiě)Microsoft Excel OOXML格式檔案的功能。
- HWPF - 提供讀寫(xiě)Microsoft Word格式檔案的功能。
- HSLF - 提供讀寫(xiě)Microsoft PowerPoint格式檔案的功能。
- HDGF - 提供讀寫(xiě)Microsoft Visio格式檔案的功能。
2.3.2 對(duì)象
本文主要介紹HSSF和XSSF兩種組件,簡(jiǎn)單的講HSSF用來(lái)操作Office 2007版本前excel.xls文件,XSSF用來(lái)操作Office 2007版本后的excel.xlsx文件,注意二者的后綴是不一樣的。
HSSF在org.apache.poi.hssf.usermodel包中。它實(shí)現(xiàn)了Workbook 接口,用于Excel文件中的.xls格式
常用組件:
HSSFWorkbook excel的文檔對(duì)象
HSSFSheet excel的表單
HSSFRow excel的行
HSSFCell excel的格子單元
HSSFFont excel字體
HSSFDataFormat 日期格式
HSSFHeader sheet頭
HSSFFooter sheet尾(只有打印的時(shí)候才能看到效果)
樣式:
HSSFCellStyle cell樣式
輔助操作包括:
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 錯(cuò)誤信息表
XSSF在org.apache.xssf.usemodel包,并實(shí)現(xiàn)Workbook接口,用于Excel文件中的.xlsx格式
常用組件:
XSSFWorkbook excel的文檔對(duì)象
XSSFSheet excel的表單
XSSFRow excel的行
XSSFCell excel的格子單元
XSSFFont excel字體
XSSFDataFormat 日期格式
和HSSF類(lèi)似;
2.3.3 兩個(gè)組件共同的字段類(lèi)型描述
其實(shí)兩個(gè)組件就是針對(duì)excel的兩種格式,大部分的操作都是相同的。
單元格類(lèi)型 描述 CELL_TYPE_BLANK 代表空白單元格 CELL_TYPE_BOOLEAN 代表布爾單元(true或false) CELL_TYPE_ERROR 表示在單元的誤差值 CELL_TYPE_FORMULA 表示一個(gè)單元格公式的結(jié)果 CELL_TYPE_NUMERIC 表示對(duì)一個(gè)單元的數(shù)字?jǐn)?shù)據(jù) CELL_TYPE_STRING 表示對(duì)一個(gè)單元串(文本)
2.3.4 操作步驟
以HSSF為例,XSSF操作相同。
首先,理解一下一個(gè)Excel的文件的組織形式,一個(gè)Excel文件對(duì)應(yīng)于一個(gè)workbook(HSSFWorkbook),一個(gè)workbook可以有多個(gè)sheet(HSSFSheet)組成,一個(gè)sheet是由多個(gè)row(HSSFRow)組成,一個(gè)row是由多個(gè)cell(HSSFCell)組成。
1、用HSSFWorkbook打開(kāi)或者創(chuàng)建“Excel文件對(duì)象”
2、用HSSFWorkbook對(duì)象返回或者創(chuàng)建Sheet對(duì)象
3、用Sheet對(duì)象返回行對(duì)象,用行對(duì)象得到Cell對(duì)象
4、對(duì)Cell對(duì)象讀寫(xiě)。
三、代碼操作
3.1 效果圖
慣例,貼代碼前先看效果圖
Excel文件兩種格式各一個(gè):


代碼結(jié)構(gòu):

導(dǎo)入后:(我導(dǎo)入了兩遍,沒(méi)做校驗(yàn))

導(dǎo)出效果:

3.2 代碼詳解
這里我以Spring+SpringMVC+Mybatis為基礎(chǔ)
Controller:
package com.allan.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.allan.pojo.Student;
import com.allan.service.StudentService;
/**
*
* @author 小賣(mài)鋪的老爺爺
*
*/
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
/**
* 批量導(dǎo)入表單數(shù)據(jù)
*
* @param request
* @param myfile
* @return
*/
@RequestMapping(value="/importExcel",method=RequestMethod.POST)
public String importExcel(@RequestParam("myfile") MultipartFile myFile) {
ModelAndView modelAndView = new ModelAndView();
try {
Integer num = studentService.importExcel(myFile);
} catch (Exception e) {
modelAndView.addObject("msg", e.getMessage());
return "index";
}
modelAndView.addObject("msg", "數(shù)據(jù)導(dǎo)入成功");
return "index";
}
@RequestMapping(value="/exportExcel",method=RequestMethod.GET)
public void exportExcel(HttpServletResponse response) {
try {
studentService.exportExcel(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Service
package com.allan.service.impl;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.allan.mapper.StudentMapper;
import com.allan.pojo.Student;
import com.allan.service.StudentService;
/**
*
* @author 小賣(mài)鋪的老爺爺
*
*/
@Service
public class StudentServiceImpl implements StudentService{
private final static String XLS = "xls";
private final static String XLSX = "xlsx";
@Autowired
private StudentMapper studentMapper;
/**
* 導(dǎo)入Excel,兼容xls和xlsx
*/
@SuppressWarnings("resource")
public Integer importExcel(MultipartFile myFile) throws Exception {
// 1、用HSSFWorkbook打開(kāi)或者創(chuàng)建“Excel文件對(duì)象”
//
// 2、用HSSFWorkbook對(duì)象返回或者創(chuàng)建Sheet對(duì)象
//
// 3、用Sheet對(duì)象返回行對(duì)象,用行對(duì)象得到Cell對(duì)象
//
// 4、對(duì)Cell對(duì)象讀寫(xiě)。
//獲得文件名
Workbook workbook = null ;
String fileName = myFile.getOriginalFilename();
if(fileName.endsWith(XLS)){
//2003
workbook = new HSSFWorkbook(myFile.getInputStream());
}else if(fileName.endsWith(XLSX)){
//2007
workbook = new XSSFWorkbook(myFile.getInputStream());
}else{
throw new Exception("文件不是Excel文件");
}
Sheet sheet = workbook.getSheet("Sheet1");
int rows = sheet.getLastRowNum();// 指的行數(shù),一共有多少行+
if(rows==0){
throw new Exception("請(qǐng)?zhí)顚?xiě)數(shù)據(jù)");
}
for (int i = 1; i <= rows+1; i++) {
// 讀取左上端單元格
Row row = sheet.getRow(i);
// 行不為空
if (row != null) {
// **讀取cell**
Student student = new Student();
//姓名
String name = getCellValue(row.getCell(0));
student.setName(name);
//班級(jí)
String classes = getCellValue(row.getCell(1));
student.setClasses(classes);
//分?jǐn)?shù)
String scoreString = getCellValue(row.getCell(2));
if (!StringUtils.isEmpty(scoreString)) {
Integer score = Integer.parseInt(scoreString);
student.setScore(score);
}
//考試時(shí)間
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小寫(xiě)的mm表示的是分鐘
String dateString = getCellValue(row.getCell(3));
if (!StringUtils.isEmpty(dateString)) {
Date date=sdf.parse(dateString);
student.setTime(date);
}
studentMapper.insert(student);
}
}
return rows-1;
}
/**
* 獲得Cell內(nèi)容
*
* @param cell
* @return
*/
public String getCellValue(Cell cell) {
String value = "";
if (cell != null) {
// 以下是判斷數(shù)據(jù)的類(lèi)型
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 數(shù)字
value = cell.getNumericCellValue() + "";
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
value = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
value = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
value = "非法字符";
break;
default:
value = "未知類(lèi)型";
break;
}
}
return value.trim();
}
/**
* 導(dǎo)出excel文件
*/
public void exportExcel(HttpServletResponse response) throws Exception {
// 第一步,創(chuàng)建一個(gè)webbook,對(duì)應(yīng)一個(gè)Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一個(gè)sheet,對(duì)應(yīng)Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("Sheet1");
// 第三步,在sheet中添加表頭第0行,注意老版本poi對(duì)Excel的行數(shù)列數(shù)有限制short
HSSFRow row = sheet.createRow(0);
// 第四步,創(chuàng)建單元格,并設(shè)置值表頭 設(shè)置表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創(chuàng)建一個(gè)居中格式
HSSFCell cell = row.createCell(0);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("班級(jí)");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("分?jǐn)?shù)");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("時(shí)間");
cell.setCellStyle(style);
// 第五步,寫(xiě)入實(shí)體數(shù)據(jù) 實(shí)際應(yīng)用中這些數(shù)據(jù)從數(shù)據(jù)庫(kù)得到,
List<Student> list = studentMapper.selectAll();
for (int i = 0; i < list.size(); i++){
row = sheet.createRow(i + 1);
Student stu = list.get(i);
// 第四步,創(chuàng)建單元格,并設(shè)置值
row.createCell(0).setCellValue(stu.getName());
row.createCell(1).setCellValue(stu.getClasses());
row.createCell(2).setCellValue(stu.getScore());
cell = row.createCell(3);
cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(stu.getTime()));
}
//第六步,輸出Excel文件
OutputStream output=response.getOutputStream();
response.reset();
long filename = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設(shè)置日期格式
String fileName = df.format(new Date());// new Date()為獲取當(dāng)前系統(tǒng)時(shí)間
response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
response.setContentType("application/msexcel");
wb.write(output);
output.close();
}
}
3.3 導(dǎo)出文件api補(bǔ)充
大家可以看到上面service的代碼只是最基本的導(dǎo)出。
在實(shí)際應(yīng)用中導(dǎo)出的Excel文件往往需要閱讀和打印的,這就需要對(duì)輸出的Excel文檔進(jìn)行排版和樣式的設(shè)置,主要操作有合并單元格、設(shè)置單元格樣式、設(shè)置字體樣式等。
3.3.1 單元格合并
使用HSSFSheet的addMergedRegion()方法
public int addMergedRegion(CellRangeAddress region)
參數(shù)CellRangeAddress 表示合并的區(qū)域,構(gòu)造方法如下:依次表示起始行,截至行,起始列, 截至列
CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol)
3.3.2 設(shè)置單元格的行高和列寬
HSSFSheet sheet=wb.createSheet(); sheet.setDefaultRowHeightInPoints(10);//設(shè)置缺省列高sheet.setDefaultColumnWidth(20);//設(shè)置缺省列寬 //設(shè)置指定列的列寬,256 * 50這種寫(xiě)法是因?yàn)閣idth參數(shù)單位是單個(gè)字符的256分之一 sheet.setColumnWidth(cell.getColumnIndex(), 256 * 50);
3.3.3 設(shè)置單元格樣式
1、創(chuàng)建HSSFCellStyle
HSSFCellStyle cellStyle=wkb.createCellStyle()
2、設(shè)置樣式
// 設(shè)置單元格的橫向和縱向?qū)R方式,具體參數(shù)就不列了,參考HSSFCellStyle
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
/* 設(shè)置單元格的填充方式,以及前景顏色和背景顏色
三點(diǎn)注意:
1.如果需要前景顏色或背景顏色,一定要指定填充方式,兩者順序無(wú)所謂;
2.如果同時(shí)存在前景顏色和背景顏色,前景顏色的設(shè)置要寫(xiě)在前面;
3.前景顏色不是字體顏色。
*/
//設(shè)置填充方式(填充圖案)
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);
//設(shè)置前景色
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
//設(shè)置背景顏色
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
// 設(shè)置單元格底部的邊框及其樣式和顏色
// 這里僅設(shè)置了底邊邊框,左邊框、右邊框和頂邊框同理可設(shè)
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);
//設(shè)置日期型數(shù)據(jù)的顯示樣式
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
3、將樣式應(yīng)用于單元格
cell.setCellStyle(cellStyle); //將樣式應(yīng)用到行,但有些樣式只對(duì)單元格起作用 row.setRowStyle(cellStyle);
3.3.4設(shè)置字體樣式
1、創(chuàng)建HSSFFont對(duì)象(調(diào)用HSSFWorkbook 的createFont方法)
HSSFWorkbook wb=new HSSFWorkbook(); HSSFFont fontStyle=wb.createFont(); HSSFWorkbook wb=new HSSFWorkbook ();
2、設(shè)置字體各種樣式
//設(shè)置字體樣式
fontStyle.setFontName("宋體");
//設(shè)置字體高度
fontStyle.setFontHeightInPoints((short)20);
//設(shè)置字體顏色
font.setColor(HSSFColor.BLUE.index);
//設(shè)置粗體
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//設(shè)置斜體
font.setItalic(true);
//設(shè)置下劃線(xiàn)
font.setUnderline(HSSFFont.U_SINGLE);
3、將字體設(shè)置到單元格樣式
//字體也是單元格格式的一部分,所以從屬于HSSFCellStyle // 將字體對(duì)象賦值給單元格樣式對(duì)象 cellStyle.setFont(font); // 將單元格樣式應(yīng)用于單元格 cell.setCellStyle(cellStyle);
大家可以看出用poi導(dǎo)出文件還是比較麻煩的,等下次在為大家介紹下irport的方法。
導(dǎo)出的api基本上就是這些,最后也希望上文對(duì)大家能有所幫助。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Java?@Autowired報(bào)錯(cuò)原因分析和4種解決方案
這篇文章主要介紹了Java?@Autowired報(bào)錯(cuò)原因分析和4種解決方案,文章圍繞主題展開(kāi)詳細(xì)內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考以一下2022-05-05
mybatis雙重foreach如何實(shí)現(xiàn)遍歷map中的兩個(gè)list數(shù)組
本文介紹了如何解析前端傳遞的JSON字符串并在Java后臺(tái)動(dòng)態(tài)構(gòu)建SQL查詢(xún)條件,首先,通過(guò)JSONArray.fromObject()將JSON字符串轉(zhuǎn)化為JSONArray對(duì)象,遍歷JSONArray,從中提取name和infos,構(gòu)建成Map對(duì)象用于Mybatis SQL映射2024-09-09
eclipse+jdk安裝以及會(huì)遇到的問(wèn)題及解決方法
這篇文章主要介紹了eclipse+jdk安裝以及會(huì)遇到的問(wèn)題+解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
springboot時(shí)間格式化的五種方法總結(jié)(解決后端傳給前端的時(shí)間顯示不一致)
這篇文章主要給大家介紹了關(guān)于springboot時(shí)間格式化的五種方法,文中介紹的方法解決了后端傳給前端的時(shí)間顯示不一致,文中通過(guò)圖文以及代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
教大家使用java實(shí)現(xiàn)頂一下踩一下功能
這篇文章主要教大家如何使用java實(shí)現(xiàn)頂一下踩一下功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
SpringCloud中的Ribbon負(fù)載均衡詳細(xì)解讀
這篇文章主要介紹了SpringCloud中的Ribbon負(fù)載均衡詳細(xì)解讀,當(dāng)系統(tǒng)面臨大量的用戶(hù)訪(fǎng)問(wèn),負(fù)載過(guò)高的時(shí)候,通常會(huì)增加服務(wù)器數(shù)量來(lái)進(jìn)行橫向擴(kuò)展(集群),多個(gè)服務(wù)器的負(fù)載需要均衡,以免出現(xiàn)服務(wù)器負(fù)載不均衡,部分服務(wù)器負(fù)載較大,部分服務(wù)器負(fù)載較小的情況,需要的朋友可以參考下2023-11-11
Spring為何需要三級(jí)緩存解決循環(huán)依賴(lài)詳解
這篇文章主要給大家介紹了關(guān)于Spring為何需要三級(jí)緩存解決循環(huán)依賴(lài),而不是二級(jí)緩存的相關(guān)資料,這個(gè)也是一個(gè)Spring的高頻面試題,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-02-02
SpringBoot環(huán)境Druid數(shù)據(jù)源使用及特點(diǎn)
Druid 是目前比較流行的高性能的,分布式列存儲(chǔ)的OLAP框架(具體來(lái)說(shuō)是MOLAP)。本文給大家分享SpringBoot環(huán)境Druid數(shù)據(jù)源使用及特點(diǎn)介紹,感興趣的朋友跟隨小編一起看看吧2021-07-07
Java gRPC攔截器簡(jiǎn)單實(shí)現(xiàn)分布式日志鏈路追蹤器過(guò)程詳解
有請(qǐng)求的發(fā)送、處理,當(dāng)然就會(huì)有攔截器的需求,例如在服務(wù)端通過(guò)攔截器統(tǒng)一進(jìn)行請(qǐng)求認(rèn)證等操作,這些就需要攔截器來(lái)完成,今天松哥先和小伙伴們來(lái)聊一聊gRPC中攔截器的基本用法,后面我再整一篇文章和小伙伴們做一個(gè)基于攔截器實(shí)現(xiàn)的JWT認(rèn)證的gRPC2023-03-03

