Java POI 读写Excel 文件简单实现
来源:互联网 发布:mac os x10.11安装 编辑:程序博客网 时间:2024/05/21 22:31
整理FileUtils的一些方法,只是一些初步实现,刚写完就挂上来了…
友情提示:**过于结构化,没太多润色....码的不好还请诸位海涵并多提意见**
关联的类型
如果有其他需求可参考官方文档:http://poi.apache.org/apidocs/index.html?overview-summary.html
jar包预览:
下载地址:http://download.csdn.net/detail/u013591605/9898273
概述
- 读取:
利用WorkbookFactory 构建一个Workbook对象,按次生成Sheet[1…255]03版,[1…n]07版.根据数据源容器(size)创建对应行(row)的个数rowNumber = size+1(保留一个title),可以理解为一个row代表一个Object,而对应行(row)所包含的单元格(Cell)就是Object的成员属性. - 写入:
与读取方法不同的事,写入根据实际需求决定是哪种文件格式,另外Cell.setCellStyle()可以定义单元格的外观,换句话说,写入的时候如果将写入的数据只是作为一般存储,也没必要纠结于样式. - Excel 提供的6中参数类型:
代码部分
读取Excel文件
public static <T> Map<String, List<? extends T>> readExcel(String path, Class clzz) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); List<T> list = new LinkedList<T>(); Map<String, List<? extends T>> map = new HashMap<String, List<? extends T>>(); File file = new File(path); FileInputStream fis = null; Workbook workBook = null; if (file.exists()) { try { fis = new FileInputStream(file); workBook = WorkbookFactory.create(fis); int numberOfSheets = workBook.getNumberOfSheets(); for (int s = 0; s < numberOfSheets; s++) { // sheet工作表 Sheet sheetAt = workBook.getSheetAt(s);// String sheetName = sheetAt.getSheetName(); //获取工作表名称 int rowsOfSheet = sheetAt.getPhysicalNumberOfRows(); // 获取当前Sheet的总列数 System.out.println("当前表格的总行数:" + rowsOfSheet); for (int r = 0; r < rowsOfSheet; r++) { // 总行 Row row = sheetAt.getRow(r); if (row == null) { continue; } else { int rowNum = row.getRowNum(); System.out.println("当前行:" + rowNum); int numberOfCells = row.getPhysicalNumberOfCells(); for (int c = 0; c < numberOfCells; c++) { // 总列(格) Cell cell = row.getCell(c); if (cell == null) { continue; } else { int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_STRING: // 代表文本 String stringCellValue = cell.getStringCellValue(); System.out.print(stringCellValue + "\t"); break; case Cell.CELL_TYPE_BLANK: // 空白格 String stringCellBlankValue = cell.getStringCellValue(); System.out.print(stringCellBlankValue + "\t"); break; case Cell.CELL_TYPE_BOOLEAN: // 布尔型 boolean booleanCellValue = cell.getBooleanCellValue(); System.out.print(booleanCellValue + "\t"); break; case Cell.CELL_TYPE_NUMERIC: // 数字||日期 boolean cellDateFormatted = DateUtil.isCellDateFormatted(cell); if (cellDateFormatted) { Date dateCellValue = cell.getDateCellValue(); System.out.print(sdf.format(dateCellValue) + "\t"); } else { double numericCellValue = cell.getNumericCellValue(); System.out.print(numericCellValue + "\t"); } break; case Cell.CELL_TYPE_ERROR: // 错误 byte errorCellValue = cell.getErrorCellValue(); System.out.print(errorCellValue + "\t"); break; case Cell.CELL_TYPE_FORMULA: // 公式 int cachedFormulaResultType = cell.getCachedFormulaResultType(); System.out.print(cachedFormulaResultType + "\t"); break; } } } System.out.println(" \t "); } System.out.println(""); } } if (fis != null) { fis.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("文件不存在!"); } return map; }
写入Excel
@SuppressWarnings("resource") public static <T> void writeExcel(String path, List<T> list, Class<T> clzz) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Field[] declaredFields = clzz.getDeclaredFields(); File file = new File(path); FileOutputStream fos = null; Workbook workbook = null; try { if (file.exists()) { fos = new FileOutputStream(file); String suffix = getSuffix(path); if (suffix.equalsIgnoreCase("XLSX")) { workbook = new XSSFWorkbook(); } else if (suffix.equalsIgnoreCase("XLS")) { workbook = new HSSFWorkbook(); } else { throw new Exception("当前文件不是excel文件"); } Sheet sheet = workbook.createSheet(); // 生成工作表 Row row = sheet.createRow(0); for (int m = 0; m < declaredFields.length; m++) { // 设置title Field field = declaredFields[m]; field.setAccessible(true); Cell cell = row.createCell(m); String name = field.getName(); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(name); } for (int i = 0; i < list.size(); i++) { // 数据 T instance = list.get(i); row = sheet.createRow(i + 1); for (int j = 0; j < declaredFields.length; j++) { Field field = declaredFields[j]; Object value = field.get(instance); String fieldTypeName = field.getGenericType().getTypeName(); field.setAccessible(true); Cell cell = row.createCell(j); switch (fieldTypeName) {// content case "long": double d = Double.valueOf(value.toString()); cell.setCellValue(d); break; case "float": CellStyle floatStyle = workbook.createCellStyle(); short format = workbook.createDataFormat().getFormat(".00");// 保留2位精度 floatStyle.setDataFormat(format); double d1 = Double.parseDouble(String.valueOf(value)); cell.setCellStyle(floatStyle); cell.setCellValue(d1); break; case "int": double d2 = Double.parseDouble(String.valueOf(value)); cell.setCellValue(d2); break; case "java.util.Date": CellStyle dateStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat("yyyy-mm-dd"); dateStyle.setDataFormat(df); cell.setCellStyle(dateStyle); String format2 = sdf.format(value); Date date = sdf.parse(format2); cell.setCellValue(date); break; case "java.lang.String": cell.setCellValue(value.toString()); break; } } workbook.write(fos); } } else { if (file.createNewFile()) { writeExcel(path, list, clzz); } else { System.out.println("创建Excel表格失败!"); } } if (fos != null) { fos.close(); } } catch (Exception e) { e.printStackTrace(); } }
截取文件后缀
public static String getSuffix(String path) { String substring = path.substring(path.lastIndexOf(".") + 1); return substring; }
初步实现大概就是这样,还有很多不完善的地方:
- 比如数据类型对应(本人用的校验不完善);
- 还有就是读写效率与性能优化;
- 数据同步,避免脏读脏写;
- 其它的以后补充…
阅读全文
0 0
- Java POI 读写Excel 文件简单实现
- 使用POI实现Java读写Excel文件
- 简单实现poi来实现读写Excel文件
- poi实现Excel文件读写
- Java POI读写Excel文件
- JAVA POI读写excel简单应用
- POI简单读写excel
- Apache POI 实现对 Excel 文件读写
- java EXCEL文件读写工具包POI
- Java通过POI读写Excel文件
- Java通过POI读写Excel文件
- Java通过POI读写Excel文件
- Java通过POI读写Excel文件
- Java通过POI读写Excel文件
- POI读写Excel文件
- POI读写Excel文件
- POI读写Excel文件
- POI读写Excel文件
- ChaosVPN简要配置过程
- 游戏CS:GO VAC反外挂系统分析
- STM32控制编码器
- the import cannot be resolved问题
- exploit-exercise的protostar之stack0
- Java POI 读写Excel 文件简单实现
- 合并两个有序链表/链表反转(逆置)/找链表倒数第k点(遍历一次)
- Codeforces Round #424 (Div. 2, rated, based on VK Cup Finals)
- 从fibonacci数列对比C语言和其对应的汇编代码
- java中基于循环嵌套的使用例题经典
- 75. could not initialize proxy
- HW--Church numerals
- 用了一年时间才大致把导师的 java 代码 看懂
- PyCharm中出现No tests were found的一种解决方法及PyCharm建立测试类的官方原文及翻译