工作用到的的两种报表导入方法
两种方法都是给予poi的
the one:
工作需要,导入几分不同的excel 文件 ,然后一个前辈给了一个半成品的工具类,用了一下,发现只有一部分功能,后来又自己重写成了一个通用的工具类,可以自动将excel数据封装成bean
不多说直接贴代码
package com.yida.common.utils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import com.yida.ad.budget1.entity.DiffActualBudget; import com.yida.xmlfee.entity.TBudgetSummary; public class ExcelReaderUtil { private POIFSFileSystem fs; private HSSFWorkbook wb; private HSSFSheet sheet; private HSSFRow row; /** * 读取Excel表格表头的内容 * * @param InputStream * @param titNum * 标题所在的行号 * @return String 表头内容的数组 */ public String[] readExcelTitle(InputStream is, int titNum) { try { fs = new POIFSFileSystem(is); wb = new HSSFWorkbook(fs); } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); row = sheet.getRow(titNum); // 标题总列数 int colNum = row.getPhysicalNumberOfCells(); System.out.println("colNum:" + colNum); String[] title = new String[colNum]; for (int i = 0; i < colNum; i++) { // title[i] = getStringCellValue(row.getCell((short) i)); title[i] = getCellFormatValue(row.getCell(i)); } return title; } /** * 读取Excel数据内容 * * @param InputStream * @param dataRow * 数据开始的行号 * @return Map 包含单元格数据内容的Map对象 */ public Map<Integer, String> readExcelContent(InputStream is, int dataRow,int rowCount) { Map<Integer, String> content = new HashMap<Integer, String>(); String str = ""; try { fs = new POIFSFileSystem(is); wb = new HSSFWorkbook(fs); } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); // 得到总行数 int rowNum = sheet.getLastRowNum(); row = sheet.getRow(0); int colNum = rowCount; // 正文内容应该从第二行开始,第一行为表头的标题 for (int i = dataRow; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; while (j < colNum) { if(row ==null||row.getCell(0)==null||"".equals(row.getCell(0))){ break; } // 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据 // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean // str += getStringCellValue(row.getCell((short) j)).trim() + // "-"; str += getCellFormatValue(row.getCell(j)).trim() + "-"; j++; } content.put(i, str); str = ""; } return content; } /** * 获取单元格数据内容为字符串类型的数据 * * @param cell * Excel单元格 * @return String 单元格数据内容 */ public String getStringCellValue(HSSFCell cell) { String strCell = ""; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: strCell = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: strCell = String.valueOf(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: strCell = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: strCell = ""; break; default: strCell = ""; break; } if (strCell.equals("") || strCell == null) { return ""; } if (cell == null) { return ""; } return strCell; } /** * 获取单元格数据内容为日期类型的数据 * * @param cell * Excel单元格 * @return String 单元格数据内容 */ private String getDateCellValue(HSSFCell cell) { String result = ""; try { int cellType = cell.getCellType(); if (cellType == HSSFCell.CELL_TYPE_NUMERIC) { Date date = cell.getDateCellValue(); result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate(); } else if (cellType == HSSFCell.CELL_TYPE_STRING) { String date = getStringCellValue(cell); result = date.replaceAll("[年月]", "-").replace("日", "").trim(); } else if (cellType == HSSFCell.CELL_TYPE_BLANK) { result = ""; } } catch (Exception e) { System.out.println("日期格式不正确!"); e.printStackTrace(); } return result; } /** * 根据HSSFCell类型设置数据 * * @param cell * @return */ public String getCellFormatValue(HSSFCell cell) { String cellvalue = "?"; if (cell != null) { // 判断当前Cell的Type switch (cell.getCellType()) { // 如果当前Cell的Type为NUMERIC case HSSFCell.CELL_TYPE_NUMERIC: case HSSFCell.CELL_TYPE_FORMULA: { // 判断当前的cell是否为Date if (HSSFDateUtil.isCellDateFormatted(cell)) { // 如果是Date类型则,转化为Data格式 // 方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00 // cellvalue = cell.getDateCellValue().toLocaleString(); // 方法2:这样子的data格式是不带带时分秒的:2011-10-12 Date date = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); cellvalue = sdf.format(date); } // 如果是纯数字 else { // 取得当前Cell的数值 cellvalue = String.valueOf(cell.getNumericCellValue()); } break; } // 如果当前Cell的Type为STRIN case HSSFCell.CELL_TYPE_STRING: { // 取得当前的Cell字符串 if ("".equals(cell.getRichStringCellValue().getString().trim())) { cellvalue = "?"; } else cellvalue = cell.getRichStringCellValue().getString(); break; } // 默认的Cell值 default: cellvalue = "?"; } } else { cellvalue = "?"; } return cellvalue; } /** * * @param c 需要转换的类型 * @param parmsName excel的数据对应bean的字段 {"findex","projectName","baoshenyusuan","gaisuanpifu","hejianMoney","remark"} * @param map readExcelContent()生成的map对象 * @param startCount 开始读的行 从0开始 * @return */ public static <T> List<T> getExcelBean(Class<T> c, String[] parmsName, Map map,int startCount) { List<T> list = new ArrayList<T>(); for (int j = startCount; j <= map.size()+startCount-1; j++) { String values = (String) map.get(j); String[] value = values.split("-"); T object = null; try { object = c.newInstance(); for (int i = 0; i < parmsName.length; i++) { if (!"?".equals(value[i])) { Method readMethod = ReflectUtils.getReadMethod(c, parmsName[i]); //这里用了一些同事写好的工具类,获得该参数的get方法,拿去用的时候可以自己写一个生成get方法的方法 Class<?> fieldClass = readMethod.getReturnType(); //获得返回值类型的class对象 Method writeMethod = ReflectUtils.getWriteMethod(c, //获得set方法 parmsName[i], fieldClass); if (fieldClass.isAssignableFrom(Integer.class)) { //根据不同的返回对象插入不同的数据 int aa = Integer.parseInt(value[i]); writeMethod.invoke(object, aa); } else if (fieldClass.isAssignableFrom(String.class)) { writeMethod.invoke(object, value[i]); } else if (fieldClass .isAssignableFrom(BigDecimal.class)) { BigDecimal aa = new BigDecimal(value[i]); writeMethod.invoke(object, aa); } else if (fieldClass.isAssignableFrom(Date.class)) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(value[i]); writeMethod.invoke(object, date); } else if (fieldClass.isAssignableFrom(Float.class)) { Float aa = Float.parseFloat(value[i]); writeMethod.invoke(object, aa); } } } list.add(object); } catch (Exception e) { e.printStackTrace(); } } return list; } public static void main(String[] args) { try { // 对读取Excel表格标题测试 InputStream is = new FileInputStream("e:\\222.xls"); ExcelReaderUtil excelReader = new ExcelReaderUtil(); String[] title = excelReader.readExcelTitle(is, 1); System.out.println("获得Excel表格的标题:"); for (String s : title) { System.out.print(s + " "); } System.out.println(""); System.out.println("=========================="); // 对读取Excel表格内容测试 InputStream is2 = new FileInputStream("e:\\222.xls"); int startCount=2; String[] parmsName=new String[]{"num","projectName","authorizedAmount","trialAmount", "diffTrialAmount","approvalAmount","diffApprovalAmount", "budgetAmount","diffBudgetAmount","guokuAmount"}; int rowCount=parmsName.length; Map<Integer, String> map =excelReader.readExcelContent(is2,startCount,rowCount); List<DiffActualBudget> list=ExcelReaderUtil.getExcelBean(DiffActualBudget.class, parmsName, map,startCount); } catch (FileNotFoundException e) { System.out.println("未找到指定路径的文件!"); e.printStackTrace(); } } }
以上代码有一大部分是网络上一些大神的贡献的,在此谢谢他们的无私
the tow 根据模板导入数据生成bean,使用jxsl ,但是jsls还是基于 poi的
一,导入 jxls jar包
二, 需要封装的bean
package E; //一个简单的猫 public class Cat { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Cat [name=" + name + ", age=" + age + "]"; } }
EXCEL导入模板
<?xml version="1.0" encoding="utf-8" ?> <workbook> <worksheet name="Sheet1"> <section startRow="0" endRow="1"/> <!--循环遍历 从index为2的行开始循环 --> <loop startRow="2" endRow="2" items="list" var="i" varType="E.Cat"> <section startRow="2" endRow="2"> <mapping row="2" col="0">i.name</mapping> <mapping row="2" col="1">i.age</mapping> </section>
<!-- 一旦每一行的第一列为空,则结束循环-->
<loopbreakcondition> <rowcheck offset="0"> <cellcheck offset="0"></cellcheck> </rowcheck> </loopbreakcondition> </loop> </worksheet> </workbook>
开始导入
package E; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jxls.reader.ReaderBuilder; import net.sf.jxls.reader.XLSReader; public class ExcelDemo { public static void main(String[] args) throws Exception{ FileInputStream inputXLS=new FileInputStream(new File("d:\\cat.xls")); InputStream inputXML = new BufferedInputStream(Cat.class.getResourceAsStream("cat.xml")); //读取上面的模板文件 XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML); //项目概况 List<Cat> items1 = new ArrayList<>(); Map<String, Object> beans = new HashMap<>(); beans.put("list", items1); mainReader.read(inputXLS, beans); //将数据导入集合中 for(Cat c:items1){ System.out.println(c.toString()); } } }
两种方式都可以方便的导入excel文件,可自行选择
时间: 2024-10-11 04:51:12