在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java实现文件导入导出

2016-7-29 15:41| 发布者: zhangjf| 查看: 596| 评论: 0

摘要: 文件导入导出必须代码 ExportExcel.java /** * Copyright ? 2012-2014 a href=https://github.com/thinkgem/jeesiteJeeSite/a All rights reserved. */package com.thinkgem.jeesite.common.utils.excel; import jav ...

文件导入导出必须代码

ExportExcel.java

  1. /**
  2. * Copyright ? 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
  3. */
  4. package com.thinkgem.jeesite.common.utils.excel;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.OutputStream;
  9. import java.lang.reflect.Field;
  10. import java.lang.reflect.Method;
  11. import java.text.DecimalFormat;
  12. import java.util.Collections;
  13. import java.util.Comparator;
  14. import java.util.Date;
  15. import java.util.HashMap;
  16. import java.util.LinkedHashMap;
  17. import java.util.List;
  18. import java.util.Map;
  19. import javax.servlet.http.HttpServletResponse;
  20. import org.apache.commons.lang3.StringUtils;
  21. import org.apache.poi.ss.usermodel.Cell;
  22. import org.apache.poi.ss.usermodel.CellStyle;
  23. import org.apache.poi.ss.usermodel.Comment;
  24. import org.apache.poi.ss.usermodel.DataFormat;
  25. import org.apache.poi.ss.usermodel.Font;
  26. import org.apache.poi.ss.usermodel.IndexedColors;
  27. import org.apache.poi.ss.usermodel.Row;
  28. import org.apache.poi.ss.usermodel.Sheet;
  29. import org.apache.poi.ss.usermodel.Workbook;
  30. import org.apache.poi.ss.util.CellRangeAddress;
  31. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  32. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  33. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import com.google.common.collect.Lists;
  37. import com.thinkgem.jeesite.common.utils.DateUtils;
  38. import com.thinkgem.jeesite.common.utils.Encodes;
  39. import com.thinkgem.jeesite.common.utils.Reflections;
  40. import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
  41. import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
  42. /**
  43. * 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion)
  44. * @author ThinkGem
  45. * @version 2013-04-21
  46. */
  47. public class ExportExcel {
  48. private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
  49. /**
  50. * 工作薄对象
  51. */
  52. private SXSSFWorkbook wb;
  53. /**
  54. * 工作表对象
  55. */
  56. private Sheet sheet;
  57. /**
  58. * 样式列表
  59. */
  60. private Map<String, CellStyle> styles;
  61. /**
  62. * 当前行号
  63. */
  64. private int rownum;
  65. /**
  66. * 注解列表(Object[]{ ExcelField, Field/Method })
  67. */
  68. List<Object[]> annotationList = Lists.newArrayList();
  69. /**
  70. * 字段map
  71. */
  72. LinkedHashMap<String,String> fieldMap;
  73. HashMap<String, String> dictTypes;
  74. /**
  75. * 构造函数
  76. * @param title 表格标题,传“空值”,表示无标题
  77. * @param cls 实体对象,通过annotation.ExportField获取标题
  78. */
  79. public ExportExcel(String title, Class<?> cls){
  80. this(title, cls, 1);
  81. }
  82. /**
  83. * 构造函数
  84. * @param title 表格标题,传“空值”,表示无标题
  85. * @param fieldMap,获取要导出的字段和字段标题
  86. */
  87. public ExportExcel(String title, LinkedHashMap<String,String> fieldMap){
  88. this.fieldMap = fieldMap;
  89. dictTypes = new HashMap<String,String>();
  90. // Initialize
  91. int colunm = 0;
  92. List<String> headerList = Lists.newArrayList();
  93. for (String key : fieldMap.keySet()){
  94. String t = fieldMap.get(key);
  95. HashMap<String, String> map = com.thinkgem.jeesite.common.utils.StringUtils.toMap(t, ";", "=", false);
  96. if(map.get("name") != null){
  97. t = map.get("name");
  98. }
  99. if(map.get("dictType") != null){
  100. dictTypes.put(""+(colunm), map.get("dictType"));
  101. }
  102. colunm++;
  103. headerList.add(t);
  104. }
  105. initialize(title, headerList);
  106. }
  107. /**
  108. * 构造函数
  109. * @param title 表格标题,传“空值”,表示无标题
  110. * @param cls 实体对象,通过annotation.ExportField获取标题
  111. * @param type 导出类型(1:导出数据;2:导出模板)
  112. * @param groups 导入分组
  113. */
  114. public ExportExcel(String title, Class<?> cls, int type, int... groups){
  115. // Get annotation field
  116. Field[] fs = cls.getDeclaredFields();
  117. for (Field f : fs){
  118. ExcelField ef = f.getAnnotation(ExcelField.class);
  119. if (ef != null && (ef.type()==0 || ef.type()==type)){
  120. if (groups!=null && groups.length>0){
  121. boolean inGroup = false;
  122. for (int g : groups){
  123. if (inGroup){
  124. break;
  125. }
  126. for (int efg : ef.groups()){
  127. if (g == efg){
  128. inGroup = true;
  129. annotationList.add(new Object[]{ef, f});
  130. break;
  131. }
  132. }
  133. }
  134. }else{
  135. annotationList.add(new Object[]{ef, f});
  136. }
  137. }
  138. }
  139. // Get annotation method
  140. Method[] ms = cls.getDeclaredMethods();
  141. for (Method m : ms){
  142. ExcelField ef = m.getAnnotation(ExcelField.class);
  143. if (ef != null && (ef.type()==0 || ef.type()==type)){
  144. if (groups!=null && groups.length>0){
  145. boolean inGroup = false;
  146. for (int g : groups){
  147. if (inGroup){
  148. break;
  149. }
  150. for (int efg : ef.groups()){
  151. if (g == efg){
  152. inGroup = true;
  153. annotationList.add(new Object[]{ef, m});
  154. break;
  155. }
  156. }
  157. }
  158. }else{
  159. annotationList.add(new Object[]{ef, m});
  160. }
  161. }
  162. }
  163. // Field sorting
  164. Collections.sort(annotationList, new Comparator<Object[]>() {
  165. public int compare(Object[] o1, Object[] o2) {
  166. return new Integer(((ExcelField)o1[0]).sort()).compareTo(
  167. new Integer(((ExcelField)o2[0]).sort()));
  168. };
  169. });
  170. // Initialize
  171. List<String> headerList = Lists.newArrayList();
  172. for (Object[] os : annotationList){
  173. String t = ((ExcelField)os[0]).title();
  174. // 如果是导出,则去掉注释
  175. if (type==1){
  176. String[] ss = StringUtils.split(t, "**", 2);
  177. if (ss.length==2){
  178. t = ss[0];
  179. }
  180. }
  181. headerList.add(t);
  182. }
  183. initialize(title, headerList);
  184. }
  185. /**
  186. * 构造函数
  187. * @param title 表格标题,传“空值”,表示无标题
  188. * @param headers 表头数组
  189. */
  190. public ExportExcel(String title, String[] headers) {
  191. initialize(title, Lists.newArrayList(headers));
  192. }
  193. /**
  194. * 构造函数
  195. * @param title 表格标题,传“空值”,表示无标题
  196. * @param headerList 表头列表
  197. */
  198. public ExportExcel(String title, List<String> headerList) {
  199. initialize(title, headerList);
  200. }
  201. /**
  202. * 初始化函数
  203. * @param title 表格标题,传“空值”,表示无标题
  204. * @param headerList 表头列表
  205. */
  206. private void initialize(String title, List<String> headerList) {
  207. this.wb = new SXSSFWorkbook(500);
  208. this.sheet = wb.createSheet("Export");
  209. this.styles = createStyles(wb);
  210. // Create title
  211. if (StringUtils.isNotBlank(title)){
  212. Row titleRow = sheet.createRow(rownum++);
  213. titleRow.setHeightInPoints(30);
  214. Cell titleCell = titleRow.createCell(0);
  215. titleCell.setCellStyle(styles.get("title"));
  216. titleCell.setCellValue(title);
  217. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
  218. titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
  219. }
  220. // Create header
  221. if (headerList == null){
  222. throw new RuntimeException("headerList not null!");
  223. }
  224. Row headerRow = sheet.createRow(rownum++);
  225. headerRow.setHeightInPoints(16);
  226. for (int i = 0; i < headerList.size(); i++) {
  227. Cell cell = headerRow.createCell(i);
  228. cell.setCellStyle(styles.get("header"));
  229. String[] ss = StringUtils.split(headerList.get(i), "**", 2);
  230. if (ss.length==2){
  231. cell.setCellValue(ss[0]);
  232. Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
  233. new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
  234. comment.setString(new XSSFRichTextString(ss[1]));
  235. cell.setCellComment(comment);
  236. }else{
  237. cell.setCellValue(headerList.get(i));
  238. }
  239. sheet.autoSizeColumn(i);
  240. }
  241. for (int i = 0; i < headerList.size(); i++) {
  242. int colWidth = sheet.getColumnWidth(i)*2;
  243. sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
  244. }
  245. log.debug("Initialize success.");
  246. }
  247. /**
  248. * 创建表格样式
  249. * @param wb 工作薄对象
  250. * @return 样式列表
  251. */
  252. private Map<String, CellStyle> createStyles(Workbook wb) {
  253. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  254. CellStyle style = wb.createCellStyle();
  255. style.setAlignment(CellStyle.ALIGN_CENTER);
  256. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  257. Font titleFont = wb.createFont();
  258. titleFont.setFontName("Arial");
  259. titleFont.setFontHeightInPoints((short) 16);
  260. titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
  261. style.setFont(titleFont);
  262. styles.put("title", style);
  263. style = wb.createCellStyle();
  264. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  265. style.setBorderRight(CellStyle.BORDER_THIN);
  266. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  267. style.setBorderLeft(CellStyle.BORDER_THIN);
  268. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  269. style.setBorderTop(CellStyle.BORDER_THIN);
  270. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  271. style.setBorderBottom(CellStyle.BORDER_THIN);
  272. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  273. Font dataFont = wb.createFont();
  274. dataFont.setFontName("Arial");
  275. dataFont.setFontHeightInPoints((short) 10);
  276. style.setFont(dataFont);
  277. styles.put("data", style);
  278. style = wb.createCellStyle();
  279. style.cloneStyleFrom(styles.get("data"));
  280. style.setAlignment(CellStyle.ALIGN_LEFT);
  281. styles.put("data1", style);
  282. style = wb.createCellStyle();
  283. style.cloneStyleFrom(styles.get("data"));
  284. style.setAlignment(CellStyle.ALIGN_CENTER);
  285. styles.put("data2", style);
  286. style = wb.createCellStyle();
  287. style.cloneStyleFrom(styles.get("data"));
  288. style.setAlignment(CellStyle.ALIGN_RIGHT);
  289. styles.put("data3", style);
  290. style = wb.createCellStyle();
  291. style.cloneStyleFrom(styles.get("data"));
  292. // style.setWrapText(true);
  293. style.setAlignment(CellStyle.ALIGN_CENTER);
  294. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  295. style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  296. Font headerFont = wb.createFont();
  297. headerFont.setFontName("Arial");
  298. headerFont.setFontHeightInPoints((short) 10);
  299. headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
  300. headerFont.setColor(IndexedColors.WHITE.getIndex());
  301. style.setFont(headerFont);
  302. styles.put("header", style);
  303. return styles;
  304. }
  305. /**
  306. * 添加一行
  307. * @return 行对象
  308. */
  309. public Row addRow(){
  310. return sheet.createRow(rownum++);
  311. }
  312. /**
  313. * 添加一个单元格
  314. * @param row 添加的行
  315. * @param column 添加列号
  316. * @param val 添加值
  317. * @return 单元格对象
  318. */
  319. public Cell addCell(Row row, int column, Object val){
  320. return this.addCell(row, column, val, 0, Class.class);
  321. }
  322. /**
  323. * 添加一个单元格
  324. * @param row 添加的行
  325. * @param column 添加列号
  326. * @param val 添加值
  327. * @param align 对齐方式(1:靠左;2:居中;3:靠右)
  328. * @return 单元格对象
  329. */
  330. public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
  331. Cell cell = row.createCell(column);
  332. CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
  333. try {
  334. if (val == null){
  335. cell.setCellValue("");
  336. } else if (val instanceof String) {
  337. cell.setCellValue((String) val);
  338. } else if (val instanceof Integer) {
  339. cell.setCellValue((Integer) val);
  340. } else if (val instanceof Long) {
  341. cell.setCellValue((Long) val);
  342. } else if (val instanceof Double) {
  343. cell.setCellValue(new DecimalFormat(".#####").format(val));
  344. } else if (val instanceof Float) {
  345. cell.setCellValue((Float) val);
  346. } else if (val instanceof Date) {
  347. DataFormat format = wb.createDataFormat();
  348. style.setDataFormat(format.getFormat("yyyy-MM-dd"));
  349. cell.setCellValue(DateUtils.formatDateTime((Date)val));
  350. } else {
  351. if (fieldType != Class.class){
  352. cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
  353. }else{
  354. cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
  355. "fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
  356. }
  357. }
  358. } catch (Exception ex) {
  359. log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
  360. cell.setCellValue(val.toString());
  361. }
  362. cell.setCellStyle(style);
  363. return cell;
  364. }
  365. /**
  366. * 添加数据(通过annotation.ExportField添加数据)
  367. * @return list 数据列表
  368. */
  369. public <E> ExportExcel setDataList(List<E> list){
  370. for (E e : list){
  371. int colunm = 0;
  372. Row row = this.addRow();
  373. StringBuilder sb = new StringBuilder();
  374. if(e instanceof Map){
  375. @SuppressWarnings("unchecked")
  376. Map<String,Object> map = (Map<String,Object>)e;
  377. for(String key : fieldMap.keySet()){
  378. Object value = map.get(key);
  379. String columnDictType = dictTypes.get(colunm+"");
  380. if (StringUtils.isNotBlank(columnDictType)){
  381. value = DictUtils.getDictLabel(value==null?"":value.toString(), columnDictType, "");
  382. }
  383. this.addCell(row, colunm++, value == null ? "" : value.toString(), 0, String.class);
  384. sb.append(value + ", ");
  385. }
  386. }
  387. else{
  388. for (Object[] os : annotationList){
  389. ExcelField ef = (ExcelField)os[0];
  390. Object val = null;
  391. // Get entity value
  392. try{
  393. if (StringUtils.isNotBlank(ef.value())){
  394. val = Reflections.invokeGetter(e, ef.value());
  395. }else{
  396. if (os[1] instanceof Field){
  397. val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
  398. }else if (os[1] instanceof Method){
  399. val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
  400. }
  401. }
  402. // If is dict, get dict label
  403. if (StringUtils.isNotBlank(ef.dictType())){
  404. val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
  405. }
  406. }catch(Exception ex) {
  407. // Failure to ignore
  408. log.info(ex.toString());
  409. val = "";
  410. }
  411. this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
  412. sb.append(val + ", ");
  413. }
  414. log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
  415. }
  416. }
  417. return this;
  418. }
  419. /**
  420. * 输出数据流
  421. * @param os 输出数据流
  422. */
  423. public ExportExcel write(OutputStream os) throws IOException{
  424. wb.write(os);
  425. return this;
  426. }
  427. /**
  428. * 输出到客户端
  429. * @param fileName 输出文件名
  430. */
  431. public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
  432. response.reset();
  433. response.setContentType("application/octet-stream; charset=utf-8");
  434. response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
  435. write(response.getOutputStream());
  436. return this;
  437. }
  438. /**
  439. * 输出到文件
  440. * @param fileName 输出文件名
  441. */
  442. public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
  443. FileOutputStream os = new FileOutputStream(name);
  444. this.write(os);
  445. return this;
  446. }
  447. /**
  448. * 清理临时文件
  449. */
  450. public ExportExcel dispose(){
  451. wb.dispose();
  452. return this;
  453. }
  454. }
复制代码

导出测试

  1. public static void main(String[] args) throws Throwable {
  2. List<String> headerList = Lists.newArrayList();
  3. for (int i = 1; i <= 10; i++) {
  4. headerList.add("表头"+i);
  5. }
  6. List<String> dataRowList = Lists.newArrayList();
  7. for (int i = 1; i <= headerList.size(); i++) {
  8. dataRowList.add("数据"+i);
  9. }
  10. List<List<String>> dataList = Lists.newArrayList();
  11. for (int i = 1; i <=1000000; i++) {
  12. dataList.add(dataRowList);
  13. }
  14. ExportExcel ee = new ExportExcel("表格标题", headerList);
  15. for (int i = 0; i < dataList.size(); i++) {
  16. Row row = ee.addRow();
  17. for (int j = 0; j < dataList.get(i).size(); j++) {
  18. ee.addCell(row, j, dataList.get(i).get(j));
  19. }
  20. }
  21. ee.writeFile("target/export.xlsx");
  22. ee.dispose();
  23. log.debug("Export success.");
  24. }
复制代码

ImportExcel.java

  1. /**
  2. * Copyright ? 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
  3. */
  4. package com.thinkgem.jeesite.common.utils.excel;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.lang.reflect.Field;
  10. import java.lang.reflect.Method;
  11. import java.util.Collections;
  12. import java.util.Comparator;
  13. import java.util.Date;
  14. import java.util.List;
  15. import org.apache.commons.lang3.StringUtils;
  16. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  17. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  18. import org.apache.poi.ss.usermodel.Cell;
  19. import org.apache.poi.ss.usermodel.DateUtil;
  20. import org.apache.poi.ss.usermodel.Row;
  21. import org.apache.poi.ss.usermodel.Sheet;
  22. import org.apache.poi.ss.usermodel.Workbook;
  23. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import org.springframework.web.multipart.MultipartFile;
  27. import com.google.common.collect.Lists;
  28. import com.thinkgem.jeesite.common.utils.Reflections;
  29. import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
  30. import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
  31. /**
  32. * 导入Excel文件(支持“XLS”和“XLSX”格式)
  33. * @author ThinkGem
  34. * @version 2013-03-10
  35. */
  36. public class ImportExcel {
  37. private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
  38. /**
  39. * 工作薄对象
  40. */
  41. private Workbook wb;
  42. /**
  43. * 工作表对象
  44. */
  45. private Sheet sheet;
  46. /**
  47. * 标题行号
  48. */
  49. private int headerNum;
  50. /**
  51. * 构造函数
  52. * @param path 导入文件,读取第一个工作表
  53. * @param headerNum 标题行号,数据行号=标题行号+1
  54. * @throws InvalidFormatException
  55. * @throws IOException
  56. */
  57. public ImportExcel(String fileName, int headerNum)
  58. throws InvalidFormatException, IOException {
  59. this(new File(fileName), headerNum);
  60. }
  61. /**
  62. * 构造函数
  63. * @param path 导入文件对象,读取第一个工作表
  64. * @param headerNum 标题行号,数据行号=标题行号+1
  65. * @throws InvalidFormatException
  66. * @throws IOException
  67. */
  68. public ImportExcel(File file, int headerNum)
  69. throws InvalidFormatException, IOException {
  70. this(file, headerNum, 0);
  71. }
  72. /**
  73. * 构造函数
  74. * @param path 导入文件
  75. * @param headerNum 标题行号,数据行号=标题行号+1
  76. * @param sheetIndex 工作表编号
  77. * @throws InvalidFormatException
  78. * @throws IOException
  79. */
  80. public ImportExcel(String fileName, int headerNum, int sheetIndex)
  81. throws InvalidFormatException, IOException {
  82. this(new File(fileName), headerNum, sheetIndex);
  83. }
  84. /**
  85. * 构造函数
  86. * @param path 导入文件对象
  87. * @param headerNum 标题行号,数据行号=标题行号+1
  88. * @param sheetIndex 工作表编号
  89. * @throws InvalidFormatException
  90. * @throws IOException
  91. */
  92. public ImportExcel(File file, int headerNum, int sheetIndex)
  93. throws InvalidFormatException, IOException {
  94. this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
  95. }
  96. /**
  97. * 构造函数
  98. * @param file 导入文件对象
  99. * @param headerNum 标题行号,数据行号=标题行号+1
  100. * @param sheetIndex 工作表编号
  101. * @throws InvalidFormatException
  102. * @throws IOException
  103. */
  104. public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
  105. throws InvalidFormatException, IOException {
  106. this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
  107. }
  108. /**
  109. * 构造函数
  110. * @param path 导入文件对象
  111. * @param headerNum 标题行号,数据行号=标题行号+1
  112. * @param sheetIndex 工作表编号
  113. * @throws InvalidFormatException
  114. * @throws IOException
  115. */
  116. public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
  117. throws InvalidFormatException, IOException {
  118. if (StringUtils.isBlank(fileName)){
  119. throw new RuntimeException("导入文档为空!");
  120. }else if(fileName.toLowerCase().endsWith("xls")){
  121. this.wb = new HSSFWorkbook(is);
  122. }else if(fileName.toLowerCase().endsWith("xlsx")){
  123. this.wb = new XSSFWorkbook(is);
  124. }else{
  125. throw new RuntimeException("文档格式不正确!");
  126. }
  127. if (this.wb.getNumberOfSheets()<sheetIndex){
  128. throw new RuntimeException("文档中没有工作表!");
  129. }
  130. this.sheet = this.wb.getSheetAt(sheetIndex);
  131. this.headerNum = headerNum;
  132. log.debug("Initialize success.");
  133. }
  134. /**
  135. * 获取行对象
  136. * @param rownum
  137. * @return
  138. */
  139. public Row getRow(int rownum){
  140. return this.sheet.getRow(rownum);
  141. }
  142. /**
  143. * 获取数据行号
  144. * @return
  145. */
  146. public int getDataRowNum(){
  147. return headerNum+1;
  148. }
  149. /**
  150. * 获取最后一个数据行号
  151. * @return
  152. */
  153. public int getLastDataRowNum(){
  154. return this.sheet.getLastRowNum()+headerNum;
  155. }
  156. /**
  157. * 获取最后一个列号
  158. * @return
  159. */
  160. public int getLastCellNum(){
  161. return this.getRow(headerNum).getLastCellNum();
  162. }
  163. /**
  164. * 获取单元格值
  165. * @param row 获取的行
  166. * @param column 获取单元格列号
  167. * @return 单元格值
  168. */
  169. public Object getCellValue(Row row, int column){
  170. Object val = "";
  171. try{
  172. Cell cell = row.getCell(column);
  173. if (cell != null){
  174. if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
  175. val = cell.getNumericCellValue();
  176. }else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
  177. val = cell.getStringCellValue();
  178. }else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
  179. val = cell.getCellFormula();
  180. }else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
  181. val = cell.getBooleanCellValue();
  182. }else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
  183. val = cell.getErrorCellValue();
  184. }
  185. }
  186. }catch (Exception e) {
  187. return val;
  188. }
  189. return val;
  190. }
  191. /**
  192. * 获取导入数据列表
  193. * @param cls 导入对象类型
  194. * @param groups 导入分组
  195. */
  196. public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
  197. List<Object[]> annotationList = Lists.newArrayList();
  198. // Get annotation field
  199. Field[] fs = cls.getDeclaredFields();
  200. for (Field f : fs){
  201. ExcelField ef = f.getAnnotation(ExcelField.class);
  202. if (ef != null && (ef.type()==0 || ef.type()==2)){
  203. if (groups!=null && groups.length>0){
  204. boolean inGroup = false;
  205. for (int g : groups){
  206. if (inGroup){
  207. break;
  208. }
  209. for (int efg : ef.groups()){
  210. if (g == efg){
  211. inGroup = true;
  212. annotationList.add(new Object[]{ef, f});
  213. break;
  214. }
  215. }
  216. }
  217. }else{
  218. annotationList.add(new Object[]{ef, f});
  219. }
  220. }
  221. }
  222. // Get annotation method
  223. Method[] ms = cls.getDeclaredMethods();
  224. for (Method m : ms){
  225. ExcelField ef = m.getAnnotation(ExcelField.class);
  226. if (ef != null && (ef.type()==0 || ef.type()==2)){
  227. if (groups!=null && groups.length>0){
  228. boolean inGroup = false;
  229. for (int g : groups){
  230. if (inGroup){
  231. break;
  232. }
  233. for (int efg : ef.groups()){
  234. if (g == efg){
  235. inGroup = true;
  236. annotationList.add(new Object[]{ef, m});
  237. break;
  238. }
  239. }
  240. }
  241. }else{
  242. annotationList.add(new Object[]{ef, m});
  243. }
  244. }
  245. }
  246. // Field sorting
  247. Collections.sort(annotationList, new Comparator<Object[]>() {
  248. public int compare(Object[] o1, Object[] o2) {
  249. return new Integer(((ExcelField)o1[0]).sort()).compareTo(
  250. new Integer(((ExcelField)o2[0]).sort()));
  251. };
  252. });
  253. //log.debug("Import column count:"+annotationList.size());
  254. // Get excel data
  255. List<E> dataList = Lists.newArrayList();
  256. for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
  257. E e = (E)cls.newInstance();
  258. int column = 0;
  259. Row row = this.getRow(i);
  260. StringBuilder sb = new StringBuilder();
  261. for (Object[] os : annotationList){
  262. Object val = this.getCellValue(row, column++);
  263. if (val != null){
  264. ExcelField ef = (ExcelField)os[0];
  265. // If is dict type, get dict value
  266. if (StringUtils.isNotBlank(ef.dictType())){
  267. val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
  268. //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
  269. }
  270. // Get param type and type cast
  271. Class<?> valType = Class.class;
  272. if (os[1] instanceof Field){
  273. valType = ((Field)os[1]).getType();
  274. }else if (os[1] instanceof Method){
  275. Method method = ((Method)os[1]);
  276. if ("get".equals(method.getName().substring(0, 3))){
  277. valType = method.getReturnType();
  278. }else if("set".equals(method.getName().substring(0, 3))){
  279. valType = ((Method)os[1]).getParameterTypes()[0];
  280. }
  281. }
  282. //log.debug("Import value type: ["+i+","+column+"] " + valType);
  283. try {
  284. if (valType == String.class){
  285. String s = String.valueOf(val.toString());
  286. if(StringUtils.endsWith(s, ".0")){
  287. val = StringUtils.substringBefore(s, ".0");
  288. }else{
  289. val = String.valueOf(val.toString());
  290. }
  291. }else if (valType == Integer.class){
  292. val = Double.valueOf(val.toString()).intValue();
  293. }else if (valType == Long.class){
  294. val = Double.valueOf(val.toString()).longValue();
  295. }else if (valType == Double.class){
  296. val = Double.valueOf(val.toString());
  297. }else if (valType == Float.class){
  298. val = Float.valueOf(val.toString());
  299. }else if (valType == Date.class){
  300. val = DateUtil.getJavaDate((Double)val);
  301. }else{
  302. if (ef.fieldType() != Class.class){
  303. val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
  304. }else{
  305. val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
  306. "fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
  307. }
  308. }
  309. } catch (Exception ex) {
  310. log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
  311. val = null;
  312. }
  313. // set entity value
  314. if (os[1] instanceof Field){
  315. Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
  316. }else if (os[1] instanceof Method){
  317. String mthodName = ((Method)os[1]).getName();
  318. if ("get".equals(mthodName.substring(0, 3))){
  319. mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
  320. }
  321. Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
  322. }
  323. }
  324. sb.append(val+", ");
  325. }
  326. dataList.add(e);
  327. log.debug("Read success: ["+i+"] "+sb.toString());
  328. }
  329. return dataList;
  330. }
  331. }
复制代码

导入测试

  1. public static void main(String[] args) throws Throwable {
  2. ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
  3. for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
  4. Row row = ei.getRow(i);
  5. for (int j = 0; j < ei.getLastCellNum(); j++) {
  6. Object val = ei.getCellValue(row, j);
  7. System.out.print(val+", ");
  8. }
  9. System.out.print("n");
  10. }
  11. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 13:09

Copyright 2015-2025 djqfx

返回顶部