‘create_time’ timestamp not null default current_timestamp comment ‘创建时间’’
‘update_time’ timestamp not null default current_timestamp on update current_timestamp comment ‘修改时间’
public QueryByPage getAllName(Integer currentPage, Integer pagesize) {
Page page1=PageHelper.startPage(currentPage,pagesize);
List list=new ArrayList<>();
list=creditEnhancementAccountRepository.getAllAccountInUsed(accountName);
//此处拿到total
Long total=page1.getTotal();
List List=new ArrayList<>();
PageInfo page = new PageInfo(List);
QueryByPage resultpage=new QueryByPage();
resultpage.setQueryBeanList(page.getList());
resultpage.setCurrentPage(page.getPageNum());
resultpage.setPagesize(page.getPageSize());
resultpage.setTotal(total);
return resultpage;
}
CSV工具:
public class CsvUtils {
public static String getCSVPath(List queryResponseList){
List exportData = new ArrayList
导出csv时若碰到大于16位的精度丢失问题 加"“是没用的 还是会被识别为数字 可以加”\t"在末尾
@RequestMapping(value = "/download")
@ResponseBody
public void downloadExcel(HttpServletResponse res, HttpServletRequest req) throws Exception {
String fileName = "模板" + ".xlsx";
ServletOutputStream out;
res.setContentType("multipart/form-data");
res.setCharacterEncoding("UTF-8");
res.setContentType("text/html");
String filePath = getClass().getResource("/template/excel/" + fileName).getPath();
String userAgent = req.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
}
filePath = URLDecoder.decode(filePath, "UTF-8");
res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream inputStream = new FileInputStream(filePath);
out = res.getOutputStream();
int b = 0;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1) {
// 4.写到输出流(out)中
out.write(buffer, 0, b);
}
inputStream.close();
if (out != null) {
out.flush();
out.close();
}
}
@RequestMapping(value="upload", method = RequestMethod.POST)
@ResponseBody
public ObjectResponse fileUpload(@RequestParam("file") MultipartFile srcFile,String uid) {
if (srcFile.isEmpty()) {
return new ObjectResponse("文件为空");
}
ExcelResultMap excelResultMap=new ExcelResultMap();
String res="";
try {
File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
if (!destFile.exists()) {
destFile = new File("");
}
//输出目标文件的绝对路径
SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
String times = sf_.format(new Date());
File upload = new File(destFile.getAbsolutePath(), "picture/" + times);
if (!upload.exists()) {
upload.mkdirs();
}
String storePath=upload.getAbsolutePath();
byte[] bytes = srcFile.getBytes();
Path path = Paths.get(upload.getAbsolutePath() + "/" + srcFile.getOriginalFilename());
Files.write(path, bytes);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String fileName = srcFile.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
String newFileName = uuid + "." + suffixName;
File oldFile = new File(storePath+"/"+srcFile.getOriginalFilename());
// new file
File newFile = new File(storePath+"/"+newFileName);
oldFile.renameTo(newFile);
String filePath=storePath+"/"+newFileName;
excelResultMap =XXXX;
} catch (IOException e) {
e.printStackTrace();
}
return new ObjectResponse(excelResultMap);
}
阿里EasyExcel
读:
想要从listener中获得数据 比如成功条数 失败条数
外层:
final QueryFromExcelListener queryFromExcelListener=new QueryFromExcelListener(XXXX);
listener中可以加属性和getter setter 完成处理后外层取即可
写:
easyexcel需要3.1.7版本的poi 可能导致版本冲突
若无法改变poi版本
老的基于poi3.14的写excel方法:
@Override
public String writeSuccessExcel (List XXXXList)throws Exception {
UUID uuid=UUID.randomUUID();
File file=new File("/data/timer/tmp/order/"+uuid+".xls");
// 构造List,实际开发从数据库里面获取
Map convertMap = new LinkedHashMap();
convertMap.put("列名1", "capitalOrderNo");
convertMap.put("列名2", "channelOrderNo");
// 获取要填充的数据
Map excelData = ExcelUtils.fillExcelData(convertMap,XXXXList);
// 获取头信息
List heads = (List) excelData.get("heads");
// 获取数据信息
List> dataList = (List>) excelData.get("dataList");
// 创建Excel文件
HSSFWorkbook workbook = ExcelUtils.createExcelFile(uuid.toString(), heads,dataList);
// 输出Excel文件
OutputStream out = new FileOutputStream(file);
workbook.write(out);
return file.getAbsolutePath();
}
用到的ExcelUtils
import com.alibaba.excel.util.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUtils {
/**
*
* @Title: createExcelFile
* @Description: 在填充sheet数据的时候,会需要一个空的Excel文件,用于设置Sheet信息的时候用到
* @return 一个不带有头信息,数据信息的空的excel文件
* @return: HSSFWorkbook
*/
public static HSSFWorkbook createExcelFile() {
HSSFWorkbook wb = new HSSFWorkbook();
return wb;
}
/**
*
* @Title: createExcelFile
* @Description: 创建一个空的带有头信息的excel
* @param fileName
* @param heads
* @return
* @return: HSSFWorkbook
*/
public static HSSFWorkbook createExcelFile(String fileName,
List heads) {
HSSFWorkbook wb = new HSSFWorkbook();
if (StringUtils.isEmpty(fileName) || null == heads) {
return null;
} else {
HSSFSheet sheet = wb.createSheet(fileName);
HSSFRow row = sheet.createRow(0);
// 封装头信息
for (int index = 0; index < heads.size(); index++) {
row.createCell(index).setCellValue(heads.get(index));
}
}
return wb;
}
/**
* @Title: createExcelFile
* @Description: 创建excel,带有头信息和数据
* @param fileName
* excel表格文件名称
* @param heads
* excel表格的头信息
* @param dataList
* excel表格要填充的数据
* @return
* @throws IOException
* @return: HSSFWorkbook
*/
public static HSSFWorkbook createExcelFile(String fileName,
List heads, List> dataList) {
HSSFWorkbook wb = new HSSFWorkbook();
if (StringUtils.isEmpty(fileName) || null == heads || null == dataList) {
return null;
} else {
HSSFSheet sheet = wb.createSheet(fileName);
HSSFRow row = sheet.createRow(0);
// 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
for(int i=0;i headMap = new
* LinkedHashMap(); headMap.put("指标ID",
* "indicatorId"); headMap.put("指标名称", "indicatorName");
* @param filePath
* excel文件
* @return
* @throws IOException
* @return: List>
*/
public static List> convertExcelDataToMapData(
Map convertMap, String filePath) throws IOException {
List> dataList = new ArrayList>();
Map headMap = new HashMap();
if (null == convertMap || convertMap.size() == 0
|| StringUtils.isEmpty(filePath)) {
return dataList;
} else {
InputStream input = new FileInputStream(filePath); // 建立输入流
Workbook wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheetAt(0);
Row rowIndexs = sheet.getRow(0);
int cellSize = rowIndexs.getLastCellNum();
Set keys = convertMap.keySet();
// 将对应的字段和excel的head的下标对应起来
for (String key : keys) {
for (int i = 0; i < cellSize; i++) {
Cell cell = rowIndexs.getCell(i);
if (cell != null
&& cell.getCellType() != Cell.CELL_TYPE_BLANK) {
if (key.equals(cell.getStringCellValue())) {
headMap.put(key, rowIndexs.getCell(i)
.getColumnIndex());
}
}
}
}
// 处理数据
int rowSize = sheet.getLastRowNum();
for (int i = 1; i < rowSize; i++) { // 第一行默认是表头数据,不算入计算结果
HashMap resultMap = new HashMap(); // 用于保存每一行的转换结果
Row row = sheet.getRow(i);
for (Map.Entry entry : headMap.entrySet()) {
Cell cell = row.getCell(entry.getValue());
String data = produceCellType(cell);
resultMap.put(convertMap.get(entry.getKey()), data);
}
dataList.add(resultMap);
}
}
return dataList;
}
/**
*
* @Title: convertExcelDataToMapDataWithPrimaryKey
* @Description: excel的转换,带有主键的原则。如果excel的那一行数据的表示的主键为null或者没填写。那么这一行不转换。
* 例如,下面的 指标ID可以理解为主键.//默认第一行的第一列为主键
* 将excel文件的每一行数据,转换为HashMap的形式.只转换第一个sheet的数据内容.
* @param convertMap
* 转换的准则,例如 Map headMap = new
* LinkedHashMap(); headMap.put("指标ID",
* "indicatorId"); headMap.put("指标名称", "indicatorName");
* @param filePath
* excel文件
* @return
* @throws IOException
* @return: List>
*/
public static List> convertExcelDataToMapDataWithPrimaryKey(
Map convertMap, String filePath) throws IOException {
List> dataList = new ArrayList>();
Map headMap = new HashMap();
if (null == convertMap || convertMap.size() == 0
|| StringUtils.isEmpty(filePath)) {
return dataList;
} else {
InputStream input = new FileInputStream(filePath); // 建立输入流
Workbook wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheetAt(0);
Row rowIndexs = sheet.getRow(0);
int cellSize = rowIndexs.getLastCellNum();
Set keys = convertMap.keySet();
// 将对应的字段和excel的head的下标对应起来
for (String key : keys) {
for (int i = 0; i < cellSize; i++) {
Cell cell = rowIndexs.getCell(i);
if (cell != null
&& cell.getCellType() != Cell.CELL_TYPE_BLANK) {
if (key.equals(cell.getStringCellValue())) {
headMap.put(key, rowIndexs.getCell(i)
.getColumnIndex());
}
}
}
}
// 处理数据
int rowSize = sheet.getLastRowNum();
for (int i = 1; i < rowSize; i++) { // 第一行默认是表头数据,不算入计算结果
HashMap resultMap = new HashMap(); // 用于保存每一行的转换结果
Row row = sheet.getRow(i);
Cell flagCell = row.getCell(0); // 默认第0列是每一行的主键
if (null != row && null != flagCell
&& HSSFCell.CELL_TYPE_BLANK != flagCell.getCellType()) {
for (Map.Entry entry : headMap.entrySet()) {
Cell cell = row.getCell(entry.getValue());
if (null != cell) {
String data = produceCellType(cell);
resultMap.put(convertMap.get(entry.getKey()), data);
}
}
}
// 将数据加入到,返回数值里面
dataList.add(resultMap);
}
}
return dataList;
}
/**
* @param
* @Title: convertExcelDataToClassData
* @Description: 解析excel已有的数据,以Class的形式返回.
* @param
* headNameMap.put("CID", "customerId")
* @param fileName
* excel文件
* @param class1
* 要转换的Class的类型
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IOException
* @throws NoSuchFieldException
* @throws SecurityException
* @return: List
*/
public static List convertExcelDataToClassData(
Map convertMap, String fileName, Class class1)
throws InstantiationException, IllegalAccessException, IOException,
NoSuchFieldException, SecurityException {
List objects = new ArrayList(); // 返回结果集
Map indexHashMap = new HashMap(); // 定位excel头文件cell位置
if (null == convertMap || convertMap.size() == 0
|| StringUtils.isEmpty(fileName)) {
return objects;
} else {
InputStream input = new FileInputStream(fileName); // 建立输入流
Workbook wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheetAt(0);
Row rowIndexs = sheet.getRow(0);
int cellSize = rowIndexs.getLastCellNum();
// 将对应的字段和excel的head的下标对应起来
Set keys = convertMap.keySet();
for (String key : keys) {
for (int i = 0; i < cellSize; i++) {
Cell cell = rowIndexs.getCell(i);
if (cell != null
&& cell.getCellType() != Cell.CELL_TYPE_BLANK) {
if (key.equals(produceCellType(cell))) {
indexHashMap.put(key, rowIndexs.getCell(i)
.getColumnIndex()); // 头文件push 下标位置
}
}
}
}
// 数据的封装
for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 第一行默认是下标,不算入计算结果
Row row = sheet.getRow(i);
T object = class1.newInstance();
for (Map.Entry entry : indexHashMap.entrySet()) {
Cell cell = row.getCell(entry.getValue());
String data = produceCellType(cell);
String fieldName = convertMap.get(entry.getKey());
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
// 根据Field的类型,来设置Field的内容
// 以便于适应除了String外的int,long,double,float等类型的属性
setFieldValue(object, data, field);
}
objects.add(object);
}
}
return objects;
}
/**
* @param
* @Title: convertExcelDataToClassData
* @Description: 解析excel已有的数据,以Class的形式返回.
* @param
* headNameMap.put("CID", "customerId")
* @param
* excel文件
* @param class1
* 要转换的Class的类型
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IOException
* @throws NoSuchFieldException
* @throws SecurityException
* @return: List
*/
public static List convertExcelDataToClassData(
Map convertMap, InputStream input, Class class1)
throws InstantiationException, IllegalAccessException, IOException,
NoSuchFieldException, SecurityException {
List objects = new ArrayList(); // 返回结果集
Map indexHashMap = new HashMap(); // 定位excel头文件cell位置
if (null == convertMap || convertMap.size() == 0 || null == input) {
return objects;
} else {
Workbook wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheetAt(0);
Row rowIndexs = sheet.getRow(0);
int cellSize = rowIndexs.getLastCellNum();
// 将对应的字段和excel的head的下标对应起来
Set keys = convertMap.keySet();
for (String key : keys) {
for (int i = 0; i < cellSize; i++) {
Cell cell = rowIndexs.getCell(i);
if (cell != null
&& cell.getCellType() != Cell.CELL_TYPE_BLANK) {
if (key.equals(produceCellType(cell))) {
indexHashMap.put(key, rowIndexs.getCell(i)
.getColumnIndex()); // 头文件push 下标位置
}
}
}
}
// 数据的封装
for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 第一行默认是下标,不算入计算结果
Row row = sheet.getRow(i);
T object = class1.newInstance();
for (Map.Entry entry : indexHashMap.entrySet()) {
Cell cell = row.getCell(entry.getValue());
String data = produceCellType(cell);
String fieldName = convertMap.get(entry.getKey());
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
// 根据Field的类型,来设置Field的内容
// 以便于适应除了String外的int,long,double,float等类型的属性
setFieldValue(object, data, field);
}
objects.add(object);
}
}
return objects;
}
/**
* @Title: matcheExcelIndexToDataForm
* @Description: 解析excel已数组的形式返回
* @param headNameMap
* headNameMap.put("CID", "customerId")
* @param fileName
* @param class1
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IOException
* @throws NoSuchFieldException
* @throws SecurityException
* @return: List
catch (DataAccessException ex){
SQLException sqle = (SQLException) ex.getCause();
logger.error("",ex);
if(sqle.getErrorCode()==1062)
return 2;
//else exception
}
比如1062是有重复的错误码
BeanUtils.copyProperties(来源bean,目标bean)
来自org.springframework.beans