当初也做过这部分,但是都是网上找的教程,长久不做就搞忘了,每次都要去反复的找,就很麻烦,这里权作一个记录,方便自己以后使用。
首先由于这里是用的springboot框架,里面可以直接maven,如果没有maven,可以自行下载网上的jar包。
<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>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
方法也很简单,只需要创建一个util方法即可
public void readExcelFile(InputStream inputStream, String fileName){
/**
* 这个inputStream文件可以来源于本地文件的流,
* 也可以来源与上传上来的文件的流,也就是MultipartFile的流,
* 使用getInputStream()方法进行获取。
*/
/**
* 然后再读取文件的时候,应该excel文件的后缀名在不同的版本中对应的解析类不一样
* 要对fileName进行后缀的解析
*/
Workbook workbook = null;
try {
//判断什么类型文件
if (fileName.endsWith(".xls")) {
workbook = new HSSFWorkbook(inputStream);
} else if (fileName.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
if (workbook == null) {
return ;
} else {
//获取所有的工作表的的数量
int numOfSheet = workbook.getNumberOfSheets();
System.out.println(numOfSheet+"--->numOfSheet");
//遍历表
for (int i = 0; i < numOfSheet; i++) {
//获取一个sheet也就是一个工作本。
Sheet sheet = workbook.getSheetAt(i);
if(sheet == null) continue;
//获取一个sheet有多少Row
int lastRowNum = sheet.getLastRowNum();
if(lastRowNum == 0) continue;
Row row ;
for (int j = 1; j <= lastRowNum; j++) {
row = sheet.getRow(j);
if(row == null) {
continue;
}
//获取一个Row有多少Cell
short lastCellNum = row.getLastCellNum();
for (int k = 0; k <= lastCellNum; k++) {
if(row.getCell(k)==null) {
continue;
}
row.getCell(k).setCellType(Cell.CELL_TYPE_STRING);
String res = row.getCell(k).getStringCellValue().trim();
//打印出cell(单元格的内容)
System.out.println(res);
}
}
}
}
}
至于你是上传,还是读取本地文件,取决于自身了。
这里做一个本地文件流的例子:
InputStream is = new FileInputStream("C:\\Users\\ZYX\\Documents\\Tencent Files\\1715951653\\FileRecv\\名单.xlsx");
readExcelFile(is, "名单.xlsx");
上面是获取本地文件流,传入上述util方法即可使用了。
这里亲测可用。
至于写的方法如下:
public void writeExcel(OutputStream outputStream){
/**
* 这个outputstream可以来自与文件的输出流,
* 也可以直接输出到response的getOutputStream()里面
* 然后用户就可以直接解析到你生产的excel文件了
*/
Workbook wb = new SXSSFWorkbook(100);
//创建一个工作本
Sheet sheet = wb.createSheet("sheet");
//通过一个sheet创建一个Row
Row row = sheet.createRow(0);
for(int i =0;i<10;i++){
//通过row创建一个cell
Cell cell = row.createCell(i);
cell.setCellValue("这是第"+i+"个cell");
}
try {
wb.write(outputStream);
wb.close();
}catch (IOException e){
e.printStackTrace();
}
}
关于写的方法,没有做测试了。
不过以前做过的项目里的导出方法和上述不一样,自行根据自身需求去选择吧。里面业务逻辑可以忽略。不重要,我也懒得去删了。
/**
* 根据时间作为查询条件查询订单,然后导出excl表格
* @param request
* @return
*/
@RequestMapping(value = "/exceldetailstimedownload", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> excldetailstimedownload(HttpServletRequest request,HttpServletResponse response) {
Map<String, Object> modelMap = new HashMap<String, Object>();
Admin admin = (Admin) request.getSession().getAttribute("shop");
Shop shop = shopService.getShopByAdminId(admin.getAdminId());
Integer shopId = shop.getShopId();
String begin = HttpServletRequestUtil.getString(request, "begin");
String end = HttpServletRequestUtil.getString(request, "end");
SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ExcelData data = new ExcelData();
data.setName("报表");
List<String> titles = new ArrayList<>();
List<List<Object>> rows = new ArrayList<>();
titles.add("订单号");
titles.add("下单时间");
titles.add("商家名称");
titles.add("付款金额");
titles.add("顾客电话");
titles.add("微信昵称");
titles.add("下单详情");
titles.add("是否退款");
data.setTitles(titles);
try {
//如果开始结束都没填,则视为默认查询所有订单
if(end==null && begin==null) {
List<ShopOrder> shopOrders = shopOrderService.queryShopOrderByExcl(shopId);
for(int i=0;i<shopOrders.size();i++) {
List<Object> row = new ArrayList<>();
row.add(shopOrders.get(i).getShopOrderSnum());
row.add(fdate.format(shopOrders.get(i).getShopOrderTime()));
row.add(shopOrders.get(i).getShop().getShopName());
row.add(shopOrders.get(i).getShopOrderMoney());
row.add(shopOrders.get(i).getWechatAuth().getUserPhone());
row.add(shopOrders.get(i).getWechatAuth().getUserNickname());
row.add(shopOrders.get(i).getShopOrderDesc());
if(shopOrders.get(i).getShopOrderStatus()!=1) {
if(shopOrders.get(i).getShopOrderStatus()==3) {
row.add("退款失败");
}else {
row.add("已退款");
}
}else {
row.add("否");
}
rows.add(row);
}
data.setRows(rows);
}else if(end==null || begin==null) {
modelMap.put("success", false);
modelMap.put("errMsg", "开始/结束时间未填,请检查后重试");
return modelMap;
}else {
List<ShopOrder> shopOrders = shopOrderService.queryShopOrderByShopIdAndTimeEx(shopId, begin, end);
for(int i=0;i<shopOrders.size();i++) {
List<Object> row = new ArrayList<>();
row.add(shopOrders.get(i).getShopOrderSnum());
row.add(fdate.format(shopOrders.get(i).getShopOrderTime()));
row.add(shopOrders.get(i).getShop().getShopName());
row.add(shopOrders.get(i).getShopOrderMoney());
row.add(shopOrders.get(i).getWechatAuth().getUserPhone());
row.add(shopOrders.get(i).getWechatAuth().getUserNickname());
row.add(shopOrders.get(i).getShopOrderDesc());
if(shopOrders.get(i).getShopOrderStatus()!=1) {
if(shopOrders.get(i).getShopOrderStatus()==3) {
row.add("退款失败");
}else {
row.add("已退款");
}
}else {
row.add("否");
}
rows.add(row);
}
data.setRows(rows);
}
fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String fileName=fdate.format(new Date())+".xls";
ExcelUtils.exportExcel(response,fileName,data);
modelMap.put("success", true);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
return modelMap;
}
下面的即上述导出所需要的工具类ExcelUtils
public class ExcelUtils {
public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
exportExcel(data, response.getOutputStream());
}
public static void exportExcel(ExcelData data, OutputStream out) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
try {
String sheetName = data.getName();
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
writeExcel(wb, sheet, data);
wb.write(out);
} catch(Exception e){
e.printStackTrace();
}finally{
//此处需要关闭 wb 变量
out.close();
}
}
private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
int rowIndex = 0;
rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
autoSizeColumns(sheet, data.getTitles().size() + 1);
}
private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
int rowIndex = 0;
int colIndex = 0;
Font titleFont = wb.createFont();
titleFont.setFontName("simsun");
//titleFont.setBoldweight(Short.MAX_VALUE);
// titleFont.setFontHeightInPoints((short) 14);
titleFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle titleStyle = wb.createCellStyle();
titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
titleStyle.setFont(titleFont);
setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
Row titleRow = sheet.createRow(rowIndex);
// titleRow.setHeightInPoints(25);
colIndex = 0;
for (String field : titles) {
Cell cell = titleRow.createCell(colIndex);
cell.setCellValue(field);
cell.setCellStyle(titleStyle);
colIndex++;
}
rowIndex++;
return rowIndex;
}
private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
int colIndex = 0;
Font dataFont = wb.createFont();
dataFont.setFontName("simsun");
// dataFont.setFontHeightInPoints((short) 14);
dataFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle dataStyle = wb.createCellStyle();
dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
dataStyle.setFont(dataFont);
setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
for (List<Object> rowData : rows) {
Row dataRow = sheet.createRow(rowIndex);
// dataRow.setHeightInPoints(25);
colIndex = 0;
for (Object cellData : rowData) {
Cell cell = dataRow.createCell(colIndex);
if (cellData != null) {
cell.setCellValue(cellData.toString());
} else {
cell.setCellValue("");
}
cell.setCellStyle(dataStyle);
colIndex++;
}
rowIndex++;
}
return rowIndex;
}
private static void autoSizeColumns(Sheet sheet, int columnNumber) {
for (int i = 0; i < columnNumber; i++) {
int orgWidth = sheet.getColumnWidth(i);
sheet.autoSizeColumn(i, true);
int newWidth = (int) (sheet.getColumnWidth(i) + 100);
if (newWidth > orgWidth) {
sheet.setColumnWidth(i, newWidth);
} else {
sheet.setColumnWidth(i, orgWidth);
}
}
}
private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
style.setBorderTop(border);
style.setBorderLeft(border);
style.setBorderRight(border);
style.setBorderBottom(border);
style.setBorderColor(BorderSide.TOP, color);
style.setBorderColor(BorderSide.LEFT, color);
style.setBorderColor(BorderSide.RIGHT, color);
style.setBorderColor(BorderSide.BOTTOM, color);
}
}