import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; http://qiye.pingan.com.cn/group1/M00/00/36/CglIiV1yJCCECQzxAAAAAN3BiIc652.txt?attname=test.txt import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale; public class ImportExeclUtil { private static int totalRows = 0;// 总行数 private static int totalCells = 0;// 总列数 private static String errorInfo;// 错误信息 /** 无参构造方法 */
public ImportExeclUtil()
{
} public static int getTotalRows()
{
return totalRows;
} public static int getTotalCells()
{
return totalCells;
} public static String getErrorInfo()
{
return errorInfo;
} /**
*
* 根据流读取Excel文件
*
*
* @param inputStream
* @param isExcel2003
* @return
* @see [类、类#方法、类#成员]
*/
public List<List<String>> read(InputStream inputStream, boolean isExcel2003)
throws IOException
{ List<List<String>> dataLst = null; /** 根据版本选择创建Workbook的方式 */
Workbook wb = null; if (isExcel2003)
{
wb = new HSSFWorkbook(inputStream);
}
else
{
wb = new XSSFWorkbook(inputStream);
}
dataLst = readDate(wb); return dataLst;
} /**
*
* 读取数据
*
* @param wb
* @return
* @see [类、类#方法、类#成员]
*/
private List<List<String>> readDate(Workbook wb)
{ List<List<String>> dataLst = new ArrayList<List<String>>(); /** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0); /** 得到Excel的行数 */
totalRows = sheet.getPhysicalNumberOfRows(); /** 得到Excel的列数 */
if (totalRows >= 1 && sheet.getRow(0) != null)
{
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
} /** 循环Excel的行 */
for (int r = 0; r < totalRows; r++)
{
Row row = sheet.getRow(r);
if (row == null)
{
continue;
} List<String> rowLst = new ArrayList<>(); /** 循环Excel的列 */
for (int c = 0; c < getTotalCells(); c++)
{ Cell cell = row.getCell(c);
String cellValue = ""; if (null != cell)
{
// 以下是判断数据的类型
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
cellValue = cell.getNumericCellValue() + "";
break; case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break; case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break; case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break; case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break; default:
cellValue = "未知类型";
break;
}
} rowLst.add(cellValue);
} /** 保存第r行的第c列 */
dataLst.add(rowLst);
} return dataLst;
} /**
*
* 按指定坐标读取实体数据
* <按顺序放入带有注解的实体成员变量中>
*
* @param wb 工作簿
* @param t 实体
* @param in 输入流
* @param integers 指定需要解析的坐标
* @return T 相应实体
* @throws IOException
* @throws Exception
* @see [类、类#方法、类#成员]
*/
@SuppressWarnings("unused")
public static <T> T readDateT(Workbook wb, T t, InputStream in, Integer[]... integers)
throws IOException, Exception
{
// 获取该工作表中的第一个工作表
Sheet sheet = wb.getSheetAt(0); // 成员变量的值
Object entityMemberValue = ""; // 所有成员变量
Field[] fields = t.getClass().getDeclaredFields();
// 列开始下标
int startCell = 0; /** 循环出需要的成员 */
for (int f = 0; f < fields.length; f++)
{ fields[f].setAccessible(true);
String fieldName = fields[f].getName();
boolean fieldHasAnno = fields[f].isAnnotationPresent(IsNeeded.class);
// 有注解
if (fieldHasAnno)
{
IsNeeded annotation = fields[f].getAnnotation(IsNeeded.class);
boolean isNeeded = annotation.isNeeded(); // Excel需要赋值的列
if (isNeeded)
{ // 获取行和列
int x = integers[startCell][0] - 1;
int y = integers[startCell][1] - 1; Row row = sheet.getRow(x);
Cell cell = row.getCell(y); if (row == null)
{
continue;
} // Excel中解析的值
String cellValue = getCellValue(cell);
// 需要赋给成员变量的值
entityMemberValue = getEntityMemberValue(entityMemberValue, fields, f, cellValue);
// 赋值
PropertyUtils.setProperty(t, fieldName, entityMemberValue);
// 列的下标加1
startCell++;
}
} } return t;
} /**
*
* 读取列表数据
* <按顺序放入带有注解的实体成员变量中>
*
* @param wb 工作簿
* @param t 实体
* @param beginLine 开始行数
* @param totalcut 结束行数减去相应行数
* @return List<T> 实体列表
* @throws Exception
* @see [类、类#方法、类#成员]
*/
@SuppressWarnings("unchecked")
public static <T> List<T> readDateListT(Workbook wb, T t, int beginLine, int totalcut)
throws Exception
{
List<T> listt = new ArrayList<T>(); /** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0); /** 得到Excel的行数 */
totalRows = sheet.getPhysicalNumberOfRows(); /** 得到Excel的列数 */
if (totalRows >= 1 && sheet.getRow(0) != null)
{
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
} /** 循环Excel的行 */
for (int r = beginLine - 1; r < totalRows - totalcut; r++)
{
Object newInstance = t.getClass().newInstance();
Row row = sheet.getRow(r);
if (row == null)
{
continue;
} // 成员变量的值
Object entityMemberValue = ""; // 所有成员变量
Field[] fields = t.getClass().getDeclaredFields();
// 列开始下标
int startCell = 1; for (int f = 1; f < fields.length; f++)
{ fields[f].setAccessible(true);
String fieldName = fields[f].getName();
boolean fieldHasAnno = fields[f].isAnnotationPresent(IsNeeded.class);
// 有注解
if (fieldHasAnno)
{
IsNeeded annotation = fields[f].getAnnotation(IsNeeded.class);
boolean isNeeded = annotation.isNeeded();
// Excel需要赋值的列
if (isNeeded)
{
Cell cell = row.getCell(startCell);
String cellValue = getCellValue(cell);
entityMemberValue = getEntityMemberValue(entityMemberValue, fields, f, cellValue);
// 赋值
PropertyUtils.setProperty(newInstance, fieldName, entityMemberValue);
// 列的下标加1
startCell++;
}
} } listt.add((T)newInstance);
} return listt;
} public static <T> List<T> readDateListTFormat(Workbook wb, T t, int beginLine, int totalcut)
throws Exception
{
List<T> listt = new ArrayList<T>(); /** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0); /** 得到Excel的行数 */
totalRows = sheet.getPhysicalNumberOfRows(); /** 得到Excel的列数 */
if (totalRows >= 1 && sheet.getRow(0) != null)
{
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
} /** 循环Excel的行 */
for (int r = beginLine - 1; r < totalRows - totalcut; r++)
{
Object newInstance = t.getClass().newInstance();
Row row = sheet.getRow(r);
if (row == null)
{
continue;
} // 成员变量的值
Object entityMemberValue = ""; // 所有成员变量
Field[] fields = t.getClass().getDeclaredFields();
// 列开始下标
int startCell = 1; for (int f = 1; f < fields.length; f++)
{ fields[f].setAccessible(true);
String fieldName = fields[f].getName();
boolean fieldHasAnno = fields[f].isAnnotationPresent(IsNeeded.class);
// 有注解
if (fieldHasAnno)
{
IsNeeded annotation = fields[f].getAnnotation(IsNeeded.class);
boolean isNeeded = annotation.isNeeded();
// Excel需要赋值的列
if (isNeeded)
{
Cell cell = row.getCell(startCell);
String cellValue = getCellValue(cell);
entityMemberValue = getEntityMemberValueFormat(entityMemberValue, fields, f, cellValue);
// 赋值
PropertyUtils.setProperty(newInstance, fieldName, entityMemberValue);
// 列的下标加1
startCell++;
}
} } listt.add((T)newInstance);
} return listt;
} /**
*
* 根据Excel表格中的数据判断类型得到值
*
* @param cell
* @return
* @see [类、类#方法、类#成员]
*/
private static String getCellValue(Cell cell)
{
String cellValue = ""; if (null != cell)
{
// 以下是判断数据的类型
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell))
{
Date theDate = cell.getDateCellValue();
SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
cellValue = dff.format(theDate);
}
else
{
DecimalFormat df = new DecimalFormat("0");
cellValue = df.format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break; case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break; case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break; case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break; default:
cellValue = "未知类型";
break;
} }
return cellValue;
} /**
*
* 根据实体成员变量的类型得到成员变量的值
*
* @param realValue
* @param fields
* @param f
* @param cellValue
* @return
* @see [类、类#方法、类#成员]
*/
private static Object getEntityMemberValue(Object realValue, Field[] fields, int f, String cellValue)
{
Field field= fields[f];
String type = field.getType().getName();
switch (type)
{
case "char":
case "java.lang.Character":
case "java.lang.String":
realValue = cellValue;
break;
case "java.util.Date":
realValue = StringUtils.isBlank(cellValue) ? null : DateUtil.strToDate(cellValue, DateUtil.YYYY_MM_DD);
break;
case "java.lang.Integer":
realValue = StringUtils.isBlank(cellValue) ? null : Integer.valueOf(cellValue);
break;
case "int":
case "float":
case "double":
case "java.lang.Double":
case "java.lang.Float":
case "java.lang.Long":
case "java.lang.Short":
case "java.math.BigDecimal":
realValue = StringUtils.isBlank(cellValue) ? null : new BigDecimal(cellValue);
break;
default:
break;
}
return realValue;
} private static Object getEntityMemberValueFormat(Object realValue, Field[] fields, int f, String cellValue)
{
Field field= fields[f];
String type = field.getType().getName();
switch (type)
{
case "char":
case "java.lang.Character":
case "java.lang.String":
realValue = cellValue;
break;
case "java.util.Date":
realValue = StringUtils.isBlank(cellValue) ? null : DateUtil.strToDate(cellValue, DateUtil.YYYYMMDD);
break;
case "java.lang.Integer":
realValue = StringUtils.isBlank(cellValue) ? null : Integer.valueOf(cellValue);
break;
case "int":
case "float":
case "double":
case "java.lang.Double":
case "java.lang.Float":
case "java.lang.Long":
case "java.lang.Short":
case "java.math.BigDecimal":
realValue = StringUtils.isBlank(cellValue) ? null : new BigDecimal(cellValue);
break;
default:
break;
}
return realValue;
} /**
*
* 根据路径或文件名选择Excel版本
*
*
* @param filePathOrName
* @param in
* @return
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static Workbook chooseWorkbook(String filePathOrName, InputStream in)
throws IOException
{
/** 根据版本选择创建Workbook的方式 */
Workbook wb = null;
boolean isExcel2003 = ExcelVersionUtil.isExcel2003(filePathOrName); if (isExcel2003)
{
wb = new HSSFWorkbook(in);
}
else
{
wb = new XSSFWorkbook(in);
} return wb;
} static class ExcelVersionUtil
{ /**
*
* 是否是2003的excel,返回true是2003
*
*
* @param filePath
* @return
* @see [类、类#方法、类#成员]
*/
public static boolean isExcel2003(String filePath)
{
return filePath.matches("^.+\\.(?i)(xls)$"); } /**
*
* 是否是2007的excel,返回true是2007
*
*
* @param filePath
* @return
* @see [类、类#方法、类#成员]
*/
public static boolean isExcel2007(String filePath)
{
return filePath.matches("^.+\\.(?i)(xlsx)$"); }
} public static class DateUtil
{ // ======================日期格式化常量=====================// public static final String YYYY_MM_DDHHMMSS = "yyyy-MM-dd HH:mm:ss"; public static final String YYYY_MM_DD = "yyyy-MM-dd"; public static final String YYYY_MM = "yyyy-MM"; public static final String YYYY = "yyyy"; public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static final String YYYYMMDD = "yyyyMMdd"; public static final String YYYYMM = "yyyyMM"; public static final String YYYYMMDDHHMMSS_1 = "yyyy/MM/dd HH:mm:ss"; public static final String YYYY_MM_DD_1 = "yyyy/MM/dd"; public static final String YYYY_MM_1 = "yyyy/MM"; /**
*
* 自定义取值,Date类型转为String类型
*
* @param date 日期
* @param pattern 格式化常量
* @return
* @see [类、类#方法、类#成员]
*/
public static String dateToStr(Date date, String pattern)
{
SimpleDateFormat format = null; if (null == date) {
return null;
}
format = new SimpleDateFormat(pattern, Locale.getDefault()); return format.format(date);
} /**
* 将字符串转换成Date类型的时间
* <hr>
*
* @param s 日期类型的字符串<br>
* datePattern :YYYY_MM_DD<br>
* @return java.util.Date
*/
public static Date strToDate(String s, String pattern)
{
if (s == null)
{
return null;
}
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try
{
date = sdf.parse(s);
}
catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
} } 导入 filename 流
String fileName = res.getFileOrigName();
Workbook wb = ImportExeclUtil.chooseWorkbook(fileName, new ByteArrayInputStream(res.getContent()));
if (res.getExpressType().equals(ExpressEnum.sf.getShortName())) {
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(sheet.getFirstRowNum());
int physicalNumberOfCells = row.getPhysicalNumberOfCells();
//校验标题列是否正确
if(physicalNumberOfCells!=14){
return ResultUtil.forCheck("标题列不正确,请严格按模板导入");
}
for (int i = 0; i < physicalNumberOfCells; i++) {
Cell cell = row.getCell(i);
if(cell!=null){
if(!sfHead.get(i).equals(cell.getStringCellValue())){
return ResultUtil.forCheck("标题列不正确,请严格按模板导入");
}
} } ExpressSfBill expressSfBill = new ExpressSfBill();
//get list
List<ExpressSfBill> list = ImportExeclUtil.readDateListT(wb, expressSfBill, 2, 0); //insert db
return expressBillService.importSFBill(list); }
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.FIELD})
public @interface IsNeeded { boolean isNeeded() default true; } 导出
@GetMapping("billTemplate")
public ResponseVO billTemplate(@RequestParam(value = "expressType") String expressType, HttpServletResponse response) {
InputStream excelFileInputStream = null;
XSSFWorkbook workbook = null;
OutputStream os = null;
try {
response.reset();
if ("sf".equals(expressType)) {
String name="ShunFeng.xlsx";
ClassPathResource resource = new ClassPathResource("template" + File.separator +name);
//web浏览通过MIME类型判断文件是excel类型
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8"); // 对文件名进行处理。防止文件名乱码
// Content-disposition属性设置成以附件方式进行下载
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name,"utf-8"));
excelFileInputStream = resource.getInputStream();
workbook = new XSSFWorkbook(excelFileInputStream);
os = response.getOutputStream();
workbook.write(os);
os.flush();
return null;
} else if ("ems".equals(expressType)) {
String name="EMS.xlsx";
ClassPathResource resource = new ClassPathResource("template" + File.separator + name);
//web浏览通过MIME类型判断文件是excel类型
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8");
// 对文件名进行处理。防止文件名乱码
// Content-disposition属性设置成以附件方式进行下载
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name,"utf-8"));
excelFileInputStream = resource.getInputStream();
workbook = new XSSFWorkbook(excelFileInputStream);
os = response.getOutputStream();
workbook.write(os);
os.flush();
return null;
}else {
return ResultUtil.forError("下载模板参数不正确");
}
} catch (Exception e) {
log.error("下载模板发生异常", e);
return ResultUtil.forError("下载模板发生异常");
} finally {
try {
if (os != null) {
os.close();
}
if (workbook != null) {
workbook.close();
}
if (excelFileInputStream != null) {
excelFileInputStream.close();
}
} catch (IOException e) {
log.error(e.getMessage());
} } } ps 工具类,感谢网友的思路及部分代码。

excel 导入 下载模板 demo的更多相关文章

  1. docker 导入下载模板

    <pre name="code" class="ruby">docker:/root# cat centos-6-x86.tar.gz | dock ...

  2. excel导入、下载功能

    1.excel导入.下载功能 2.首先,我们是居于maven项目进行开发引入poi,如果不是那就手动下载相应的jar包引入项目就可以了 <!-- poi --> <dependenc ...

  3. spring boot + easypoi两行代码excel导入导出

    easypoi封装了poi让我们能够非常简单的实现Excel导出,Excel模板导出,Excel导入,Word模板导出等,具体可见官网:http://www.afterturn.cn/. 我这边实现了 ...

  4. Excel 导入时如何下载模板信息(Java)

    大家知道,我们在实现 Excel 上传的时候,会让我们去下载个模板,然后实现导入功能.在此我在这里记录下来,以便后续的使用... 首先思考一个问题是 这个模板这么给前台,还有这个模板是这么来的,刚开始 ...

  5. vue Excel导入,下载Excel模板,导出Excel

    vue  Excel导入,下载Excel模板,导出Excel vue  Excel导入,下载Excel模板 <template> <div style="display: ...

  6. 下载模板、Excel导入、导出

    下载模板 /// <summary> /// 下载模板 /// </summary> /// <returns></returns> public Ac ...

  7. C#实现Excel模板导出和从Excel导入数据

    午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.封装的Exc ...

  8. 通用的高度可扩展的Excel导入实现(附Demo)

    Demo源码 背景 通过程序将excel导入到数据库中是一项非常常见的功能.通常的做法是:先将excel转成DataTable,然后将DataTable转换成List<T>,最终通过Lis ...

  9. java动态生成带下拉框的Excel导入模板

    在实际开发中,由于业务需要,常常需要进行Excel导入导出操作.以前做一些简单的导入时,先准备一个模板,再进行导入,单有十几. 二十几个导入模板时,往往要做十几.二十几个模板.而且,当在模板中需要有下 ...

随机推荐

  1. 使用CocoaPods创建自己的私有库-iOS组件化第一步

    目前iOS组件化常用的解决方案是Pod+路由+持续集成,通常架构设计完成后第一步就是将原来工程里的模块按照架构图分解为一个个独立的pod工程(组件),今天我们就来看看如何创建一个Pod私有库. 新建: ...

  2. pytorch实现yolov3(4) 非极大值抑制nms

    在上一篇里我们实现了forward函数.得到了prediction.此时预测出了特别多的box以及各种class probability,现在我们要从中过滤出我们最终的预测box. 理解了yolov3 ...

  3. 从零到一,利用kubeadm在ubuntu server 16.04 64位系统离线安装kubernetes v1.10.0

    说明 初步接触kubernets,记录学习过程 本教程目的利用kubeadm在ubuntu server 16.04 64位系统离线安装kubernets v1.10.0 环境信息 节点IP地址 角色 ...

  4. 看看大神 Paul Graham 对如何学习编程的回答

    前言 我翻阅自己之前写的博客文章,发现在 2015 年我刚开始学习编程的时候,翻译了一段 Paul Graham 关于"How can I learn to program?"的回 ...

  5. C++学习书籍推荐《C++ Primer 第五版 (英文)》下载

    百度云及其他网盘下载地址:点我 编辑推荐 <C++ Primer(英文版)(第5版)>是全球最畅销的C++图书.这本久负盛名的C++经典教程,时隔八年之久,终迎来的重大升级.除令全球无数程 ...

  6. MyBatis where、set、trim标签的用法

    <!-- 4.3.1 where用法 <where>标签的作用:如果该便签包含的元素中有返回值,就插入一个where:如果 where后面的字符串是一and或or开头的,就将它们剔除 ...

  7. [记录] Linux登录前后提示语

    Linux登录前后提示语 /etc/issue 本地(虚拟控制台KVM等)登录前提示语,支持转义字符 /etc/issue.net 远程(telnet,ssh)登录前提示语,不支持转义字符 /etc/ ...

  8. Devops-运维效率之数据迁移自动化

    overmind系统上线三个月,累计执行任务800+,自动审核执行SQL超过5000条,效率提升相当明显,离"一杯咖啡,轻松运维"的目标又进了一步. 写在前边 overmind系统 ...

  9. 嵌入式web服务器BOA的移植及应用

    嵌入式web服务器子系统 一.嵌入式web服务器的控制流程 如下图所示,嵌入式web服务器可实现通过网络远程控制嵌入式开发板,便捷实用. 控制流程:浏览器 --->>>嵌入式开发板 ...

  10. c语言进阶5-递归算法

    一.  什么是递归 程序调用自身的编程技巧称为递归( recursion). 递归做为一种算法在程序设计语言中广泛应用. 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型 ...