You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

259 lines
10 KiB
Java

2 years ago
package com.jingcheng.cms.util;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author ybin
* @version 1.0
* @date 2021/1/22 14:51
* @description:
*/
public class ExcelUtils {
private static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
/**
*
* @param in
* @param fileName
* @return
* @throws Exception
*/
public static List getCourseListByExcel(InputStream in, String fileName) throws Exception {
List list = new ArrayList<>();
// 创建excel工作簿
Workbook work = getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet == null) {
continue;
}
// 滤过第一行标题
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if (row == null || row.getFirstCellNum() == j) {
continue;
}
List<Object> li = new ArrayList<>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
// 日期类型转换
if(y == 3) {
//cell.setCellType(CellType.STRING);
double s1 = cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(s1);
li.add(date);
continue;
}
li.add(cell);
}
list.add(li);
}
}
work.close();
return list;
}
/**
*
* @param in
* @param fileName
* @return
*/
private static Workbook getWorkbook(InputStream in, String fileName) throws Exception {
Workbook book = null;
String filetype = fileName.substring(fileName.lastIndexOf("."));
if (".xls".equals(filetype)) {
book = new HSSFWorkbook(in);
} else if (".xlsx".equals(filetype)) {
book = new XSSFWorkbook(in);
} else {
throw new Exception("请上传excel文件");
}
return book;
}
public static void export(Workbook wb, HttpServletResponse response, String tableName) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
InputStream is = null;
try {
wb.write(os);
byte[] content = os.toByteArray();
is = new ByteArrayInputStream(content);
tableName = URLEncoder.encode(tableName, "UTF-8");
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + tableName + ".xls");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
ServletOutputStream out = response.getOutputStream();
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
response.flushBuffer();
} catch (IOException e) {
throw new RuntimeException("导出数据异常", e);
} finally {
try {
bos.close();
is.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static XSSFWorkbook initExcelWorkbook(List<String> firstRow) {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("fieldSheet");
sheet.setAutobreaks(true);
XSSFCellStyle setBorder = wb.createCellStyle();
// setBorder.setAlignment(HSSFCellStyle.ALIGN_CENTER);
setBorder.setWrapText(true);
XSSFRow row = sheet.createRow(0);
//设置第一行的字段
for (int i = 0; i < firstRow.size(); i++) {
row.createCell(i).setCellValue(firstRow.get(i));
sheet.autoSizeColumn(i);
}
return wb;
}
public static XSSFWorkbook exportExcel(List<LinkedHashMap> dataList, List<String> firstRow) {
XSSFWorkbook wb = initExcelWorkbook(firstRow);
XSSFSheet sheet = wb.getSheet("fieldSheet");
for (int i = 0; i < dataList.size(); i++) {
XSSFRow row = sheet.createRow(i + 1);
LinkedHashMap<String, Object> data = dataList.get(i);
for (int j = 0; j < firstRow.size(); j++) {
String fieldName = firstRow.get(j);
String value = "";
if (data.get(fieldName) != null) {
value = String.valueOf(data.get(fieldName));
}
row.createCell(j).setCellValue(value);
}
}
for (int i = 0; i < firstRow.size(); i++) {
sheet.autoSizeColumn(i);
}
return wb;
}
/**
*@desc Excel2022-09-20easypoi4.4
*@param workbook excel
*@param strings
*@param colNum
*@author maBing
*@date 2022/9/20:10:33
*/
public static void setDataValidation(Workbook workbook, String[] strings, int colNum) {
/**4.1架包适用*/
/*DVConstraint constraint = DVConstraint.createExplicitListConstraint(strings);
CellRangeAddressList region = new CellRangeAddressList(1,100,colNum,colNum);
HSSFDataValidation hssfDataValidation = new HSSFDataValidation(region,constraint);
hssfDataValidation.setSuppressDropDownArrow(false);
workbook.getSheetAt(0).addValidationData(hssfDataValidation);*/
/**架包采用4.4改动*/
CellRangeAddressList regions = new CellRangeAddressList(1,1200,colNum,colNum);
/*XSSFDataValidation xssfDataValidation = new XSSFDataValidation(region,constraint);*/
Sheet sheet = workbook.getSheetAt(0);
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(strings);
DataValidation dataValidation = helper.createValidation(constraint, regions);
sheet.addValidationData(dataValidation);
}
public static void setDataValidation(Workbook workbook,String sheetName,int sheetIndex,int colIndex,String[] strings){
selectListMore(sheetName,sheetIndex,workbook,colIndex,colIndex,strings);
}
public static void selectListMore(String sheetName, Integer index, Workbook workbook, int firstCol, int lastCol, String[] strings ){
//将下拉框数据放到新的sheet里然后excle通过新的sheet数据加载下拉框数据
Sheet hidden = workbook.createSheet(sheetName);
//创建单元格对象
Cell cell =null;
//遍历我们上面的数组将数据取出来放到新sheet的单元格中
for (int i = 0, length = strings.length; i < length; i++){
//取出数组中的每个元素
String name = strings[i];
//根据i创建相应的行对象说明我们将会把每个元素单独放一行
Row row = hidden.createRow(i);
//创建每一行中的第一个单元格
cell = row.createCell(0);
//然后将数组中的元素赋值给这个单元格
cell.setCellValue(name);
}
// 创建名称,可被其他单元格引用
Name namedCell = workbook.createName();
namedCell.setNameName(sheetName);
// 设置名称引用的公式
namedCell.setRefersToFormula(sheetName+"!$A$1:$A$" + strings.length);
/*//加载数据,将名称为hidden的sheet中的数据转换为List形式
DVConstraint constraint = DVConstraint.createFormulaListConstraint(sheetName);
// 设置第一列的3-65534行为下拉列表
// (3, 65534, 2, 2) ====> (起始行,结束行,起始列,结束列)
CellRangeAddressList regions = new CellRangeAddressList(0, 65535, firstCol, lastCol);
// 将设置下拉选的位置和数据的对应关系 绑定到一起
DataValidation dataValidation = new HSSFDataValidation(regions, constraint);
//将第二个sheet设置为隐藏
workbook.setSheetHidden(index, true);
//将数据赋给下拉列表
workbook.getSheetAt(0).addValidationData(dataValidation);*/
/**架包采用4.4改动*/
CellRangeAddressList regions = new CellRangeAddressList(1,1200,firstCol,lastCol);
/*XSSFDataValidation xssfDataValidation = new XSSFDataValidation(region,constraint);*/
Sheet sheet = workbook.getSheetAt(0);
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(strings);
DataValidation dataValidation = helper.createValidation(constraint, regions);
sheet.addValidationData(dataValidation);
}
}