拆分导入

This commit is contained in:
gaojiabao
2023-04-03 21:11:11 +08:00
parent c52c720884
commit d3c152f5b4
10 changed files with 870 additions and 263 deletions
@@ -0,0 +1,269 @@
package com.adc.da.att.util;
import com.adc.da.util.exception.AdcDaBaseException;
import com.adc.da.util.utils.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* @Description
* @Author liyawei
* @Create 2021/7/26
*/
public class CommonExportUtil {
private static final Logger logger = LoggerFactory.getLogger(CommonExportUtil.class);
/**
* 导出excel
* @param columnList 数据库字段名集合
* @param headerList 导出表头集合
* @param datalist
* @param response
* @param request
* @param exportName
* @param tableName
* @throws Exception
*/
public static void exportExcel(List<String> columnList, List<String> headerList, List<Map<String,Object>> datalist, HttpServletResponse response, HttpServletRequest request,
String exportName, String tableName) throws Exception{
final OutputStream os = response.getOutputStream(); // 获得ServletOutputStream对象
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(exportName+".xlsx", "UTF-8") + ';');
response.setHeader("Content-Disposition",
"attachment; filename=" + ReadExcel.encodeFileName(exportName+".xlsx", request));
//导出excel
copyrightContractCount(columnList ,headerList ,datalist ,os ,tableName);
}
/**
*
* @param fileName 文件名
* @param headers 表头
* @param desc 填写说明
* @param response
* @param request
* @throws Exception
*/
public static void exportTemplate(String fileName , String[] headers , String desc, HttpServletResponse response, HttpServletRequest request) throws Exception {
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet();
//设置表格样式
XSSFCellStyle cellStyle = (XSSFCellStyle) generateCommonCellStyle(workbook,true);
OutputStream os = response.getOutputStream();
try{
// 设置表格默认列宽度为15个字节
//sheet.setDefaultColumnWidth((short) 18);
XSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
XSSFCell cell = row.createCell(i);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
cell.setCellStyle(cellStyle);
}
// 如果填写说明存在,则创建
if (StringUtils.isNotEmpty(desc)){
XSSFRow descRow = sheet.createRow(1);
descRow.setHeightInPoints(80.0F);
XSSFCell descCell = descRow.createCell(0);
descCell.setCellValue(desc);
descCell.setCellStyle(generateDescCellStyle(workbook,true));
CellRangeAddress region = new CellRangeAddress(1, 1,0,headers.length);
sheet.addMergedRegion(region);
}
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/force-download");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition",
"attachment; filename=" + ReadExcel.encodeFileName(fileName+".xlsx", request));
response.flushBuffer();
workbook.write(os);
} catch (IOException e) {
logger.error("发生异常,异常信息为:"+e.getMessage(), e);
throw new AdcDaBaseException("下载文件失败,请重试");
}finally {
workbook.close();
IOUtils.closeQuietly(os);
}
}
/**
* 导出excel
* @param columnList
* @param headerList
* @param dataList
* @param os
* @param tableName
* @throws Exception
*/
public static void copyrightContractCount(List columnList,List headerList,List dataList ,OutputStream os,String tableName) throws Exception{
try{
Workbook workbook = new XSSFWorkbook();
//产生通用单元格样式
CellStyle style = generateCommonCellStyle(workbook,false);
//创建sheet表单,同时写入标题
CellStyle titleStyle = generateCommonCellStyle(workbook,true);
Sheet sheet = generateSheet(workbook, tableName, columnList, titleStyle);
//写入标题行
writeColumnName(sheet ,headerList ,titleStyle);
//写入数据行
writeDataRow(sheet, columnList, dataList, style);
//输入excel文件
workbook.write(os);
os.close();
//os.flush();
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
logger.error("发生异常,异常信息为:"+e.getMessage(), e);
throw new AdcDaBaseException("下载文件失败,请重试");
}finally {
IOUtils.closeQuietly(os);
}
}
/**
* 表格导入数据
* @param sheet
* @param columnList
* @param dataList
* @param style
*/
public static void writeDataRow(Sheet sheet, List columnList, List<Map<String,Object>> dataList, CellStyle style){
//columnList 列数
int rowIndex = 2;
for(int i = 0 ; i<dataList.size() ;i++) {
//创建一行
Row dataRow = sheet.createRow(rowIndex++);
//获取该行数据
Map<String,Object> rowDataMap = dataList.get(i);
if (columnList != null && columnList.size() > 0) {
for (int j = 0; j < columnList.size() ;j++) {
//创建单元格
Cell dataCell = dataRow.createCell(j);
//设置单元格样式
dataCell.setCellStyle(style);
//从数据map中获取对应列的数据
if(rowDataMap.get(columnList.get(j)) == null){
continue;
}
String value = String.valueOf(rowDataMap.get(columnList.get(j)));
//将数据写入单元格
dataCell.setCellValue(value);
}
}
}
}
/**
* 第二行设置导出的列名
* @param sheet
* @param headerList
* @param style
*/
public static void writeColumnName(Sheet sheet , List<String> headerList , CellStyle style){
Row titleRow = sheet.createRow(1);
int index = 0;
for(int i = 0;i < headerList.size();i ++){
Cell titleCell = titleRow.createCell(index);
titleCell.setCellStyle(style);
titleCell.setCellValue(headerList.get(i));
index ++;
}
}
/**
* 创建sheet表单,第一行合并单元格设置表格名
* @param workbook
* @param tableName
* @param columnList
* @param style
* @return
*/
public static Sheet generateSheet(Workbook workbook, String tableName, List columnList, CellStyle style){
//创建sheet表单
Sheet sheet = workbook.createSheet(tableName);
//在表单中创建一行
Row tableRow = sheet.createRow(0);
//在行中创建单元格
for(int i = 0;i < columnList.size();i ++){
Cell cell = tableRow.createCell(i);
cell.setCellStyle(style);
}
//获取第一个单元格
Cell tableCell = tableRow.getCell(0);
//给第一个单元格添加数据
tableCell.setCellValue(tableName);
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnList.size()-1));
return sheet;
}
/**
* 设置单元格样式
* @param workbook
* @return
*/
public static CellStyle generateCommonCellStyle(Workbook workbook, boolean isBold){
//设置表格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
cellStyle.setBorderRight(BorderStyle.THIN); //右边框
cellStyle.setBorderTop(BorderStyle.THIN); //上边框
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 上下居中
cellStyle.setWrapText(true); // 设置自动换行
Font headerFont = getFont(workbook, (short) 10,isBold); // 创建字体样式
cellStyle.setFont(headerFont); // 为标题样式设置字体样式
return cellStyle;
}
/**
* 设置填写说明样式
* @param workbook
* @return
*/
public static CellStyle generateDescCellStyle(Workbook workbook, boolean isBold){
//设置表格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 上下居中
cellStyle.setWrapText(true); // 设置自动换行
Font headerFont = getFont(workbook, (short) 10,isBold); // 创建字体样式
cellStyle.setFont(headerFont); // 为标题样式设置字体样式
return cellStyle;
}
public static Font getFont(Workbook workbook, short size, boolean isBold) {
Font font = workbook.createFont();
font.setFontName("宋体"); // 字体样式
font.setBold(isBold); // 是否加粗
font.setFontHeightInPoints(size); // 字体大小
return font;
}
}
@@ -0,0 +1,175 @@
package com.adc.da.att.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* @des : excel信息读取
* @author: duyunbao
* @email: 1114808306@qq.com
* @date 2017/10/27 17:06
**/
public class ReadExcel {
private static final Logger logger = LoggerFactory.getLogger(ReadExcel.class);
/**
* 总行数
*/
private int totalRows = 0;
/**
* 总条数
*/
private int totalCells = 0;
/**
* 错误信息接收器
*/
private String errorMsg;
public ReadExcel() {
// 不做操作
}
public int getTotalRows() {
return totalRows;
}
public int getTotalCells() {
return totalCells;
}
public String getErrorInfo() {//获取错误信息
return errorMsg;
}
/**
* @method_name: validateExcel
* @des : 验证excel格式
* @author: duyunbao
* @param: [filePath]
* @return: boolean
* @date: 2017/10/27 17:07
**/
public boolean validateExcel(String filePath) {
if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
/**
* @method_name: getExcelInfo
* @des : 读EXCEL文件,获取信息集合
* @author: duyunbao
* @param: [fileName, Mfile]
* @return: org.apache.poi.ss.usermodel.Workbook
* @date: 2017/10/27 17:08
**/
public Workbook getExcelInfo(String fileName, MultipartFile Mfile) {
Workbook wb = null;
//把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; //获取本地存储路径
//初始化输入流
InputStream is = null;
try {
//根据文件名判断文件是2003版本还是2007版本
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
is = cf.getInputStream();
//根据excel里面的内容读取客户信息
wb = getExcelInfo(is, isExcel2003, wb);
is.close();
} catch (Exception e) {
logger.error(e.getMessage(),e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
logger.error(e.getMessage(),e);
}
}
}
return wb;
}
/***
* @method_name: getExcelInfo
* @des : 判断excel版本
* @author: duyunbao
* @param: [is, isExcel2003, wb]
* @return: org.apache.poi.ss.usermodel.Workbook
* @date: 2017/10/27 17:08
**/
private Workbook getExcelInfo(InputStream is, boolean isExcel2003, Workbook wb) {
Workbook workbook =wb;
try {
/** 根据版本选择创建Workbook的方式 */
//当excel是2003时
if (isExcel2003) {
workbook = new HSSFWorkbook(is);
} else {//当excel是2007时
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
return workbook;
}
/**
* 获取sheet的名称
* @MethodName:getSheetName
* @author: 马晓晨
* @email: 747052172@qq.com
* @date 2017年11月24日 上午9:49:22
* @version V1.0
* @param filename
* @param file
* @param sheetIndex
* @return
*/
public String getSheetName(String filename, MultipartFile file, Integer sheetIndex) {
Workbook wb = getExcelInfo(filename, file);
return wb.getSheetName(sheetIndex);
}
/**
*
* @Title: encodeFileName
* @Description: 导出文件转换文件名称编码
* @param @param fileNames
* @param @param request
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String encodeFileName(String fileNames , HttpServletRequest request) {
try {
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
fileNames = new String(fileNames.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
} else {
fileNames = URLEncoder.encode(fileNames, "utf-8");
//谷歌中空格变为+问题
fileNames = fileNames.replaceAll("\\+","%20");
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return fileNames ;
}
}
@@ -0,0 +1,164 @@
package com.adc.da.att.util;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
/**
* @des : excel版本判断类
* @author: duyunbao
* @email: 1114808306@qq.com
* @date 2017/10/27 16:59
**/
public class WDWUtil {
/**
* @method_name: isExcel2003
* @des :是否是2003的excel,返回true是2003
* @author: duyunbao
* @param: [filePath]
* @return: boolean
* @date: 2017/10/27 16:57
**/
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
/**
* @method_name: isExcel2007
* @des : 是否是2007的excel,返回true是2007
* @author: duyunbao
* @param: [filePath]
* @return: boolean
* @date: 2017/10/27 16:57
**/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 判断字符串是否是整数
* @MethodName:isInteger
* @author: DuYunbao
* @date: 2018/5/22 18:00
*/
public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
/**方法二:推荐,速度最快
* 判断是否为整数
* @param str 传入的字符串
* @return 是整数返回true,否则返回false
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
/**
* 字母或数字
*
* @MethodName:isLetterDigitOrChinese
* @author: DuYunbao
* @date: 2018/5/30 15:26
*/
public static boolean isLetterOrNumber(String str) {
String regex = "^(\\d|[a-zA-Z])+$";
return !str.matches(regex);
}
/**
* 汉字、字母、()
*
* @MethodName:isLetterOrChineseOrChar1
* @author: DuYunbao
* @date: 2018/5/30 15:53
*/
public static boolean isLetterOrChineseOrChar1(String str) {
String regex = "[^\\a-\\z\\A-\\Z\\u4E00-\\u9FA5\\()\\()]";
return str.matches(regex);
}
/**
* 汉字、字母、数字
*
* @MethodName:isLetterOrChineseOrNumber
* @author: DuYunbao
* @date: 2018/5/30 15:56
*/
public static boolean isLetterOrChineseOrNumber(String str) {
String regex = "^[\\u4E00-\\u9FA5A-Za-z0-9]+$";
return !str.matches(regex);
}
/**
* 汉字、字母、()、-、下划线
*
* @MethodName:isChineseOrLetterOrUnderlineOrChar1
* @author: DuYunbao
* @date: 2018/5/30 16:03
*/
public static boolean isChineseOrLetterOrUnderlineOrChar1(String str) {
String regex = "^[\\u4E00-\\u9FA5A-Za-z_\\-\\()\\()]+$";
return !str.matches(regex);
}
/**
* 数字
*
* @MethodName:isNumbee
* @author: DuYunbao
* @date: 2018/5/30 16:09
*/
public static boolean isNumber(String str) {
String regex = "\\D";
return str.matches(regex);
}
/**
* 数字、大写字母、-
*
* @MethodName:isNumberOrLowerLetterOrChar1
* @author: DuYunbao
* @date: 2018/5/30 16:41
*/
public static boolean isNumberOrLowerLetterOrChar1(String str) {
String regex = "^[A-Z0-9\\-]+$";
return !str.matches(regex);
}
/**
* 汉字、数字、字母、()、-、下划线
*
* @MethodName:isChineseOrNumberOrLetterOrUnderlineOrChar
* @author: DuYunbao
* @date: 2018/5/30 16:45
*/
public static boolean isChineseOrNumberOrLetterOrUnderlineOrChar(String str) {
String regex = "^[\\u4E00-\\u9FA5A-Za-z0-9_\\-\\()\\()]+$";
return !str.matches(regex);
}
/**
* 去除整数含有小数点
* @MethodName:subStr
* @author: DuYunbao
* @date: 2018/5/31 11:19
*/
public static String subStr(String text) {
if (StringUtils.isNotEmpty(text)) {
if(text.contains(".0") && text.substring(text.length()-2,text.length()).equals(".0")) {
text = text.substring(0,text.length()-2);
}
}
return text;
}
}
@@ -88,4 +88,6 @@ public interface DicTypeEODao extends BaseMapper<DicTypeEO> {
String selectByPid(@Param("Info") String Info);
List<DicTypeEO> selectByPidInfo(@Param("pid") String pid);
List<DicTypeEO> selectPidByCode(@Param("fileType") String fileType);
}