- 中文翻译
- 信息点
- 分 类
- 有一级类和二级类
- 中文名
- POI信息点
- POI全称
- Point of Information
-
java实现在线预览--poi实现word、excel、ppt转html
2019-07-31 18:39:43java实现在线预览- -之poi实现word、excel、ppt转htmljava实现在线预览
- -之poi实现word、excel、ppt转html
###简介
java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office、office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0
如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行,可参考这篇文章http://blog.csdn.net/z69183787/article/details/17468039,写的挺细的,实现原理就是:
1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件;
2.通过swfTools将pdf文件转换成swf格式的文件;
3.通过FlexPaper文档组件在页面上进行展示。
当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。
我这里介绍通过poi实现word、excel、ppt转html,这样就可以放在页面上了。###word转html
package wordToHtml; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.FileUtils; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.PicturesManager; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.hwpf.usermodel.Picture; import org.apache.poi.hwpf.usermodel.PictureType; import org.w3c.dom.Document; public class PoiWordToHtml { public static void main(String[] args) throws Throwable { final String path = "D:\\poi-test\\wordToHtml\\"; final String file = "人员选择系分.doc"; InputStream input = new FileInputStream(path + file); HWPFDocument wordDocument = new HWPFDocument(input); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument()); wordToHtmlConverter.setPicturesManager(new PicturesManager() { public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) { return suggestedName; } }); wordToHtmlConverter.processDocument(wordDocument); List pics = wordDocument.getPicturesTable().getAllPictures(); if (pics != null) { for (int i = 0; i < pics.size(); i++) { Picture pic = (Picture) pics.get(i); try { pic.writeImageContent(new FileOutputStream(path + pic.suggestFullFileName())); } catch (FileNotFoundException e) { e.printStackTrace(); } } } Document htmlDocument = wordToHtmlConverter.getDocument(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DOMSource domSource = new DOMSource(htmlDocument); StreamResult streamResult = new StreamResult(outStream); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "html"); serializer.transform(domSource, streamResult); outStream.close(); String content = new String(outStream.toByteArray()); FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8"); } }
###excel转html
package excelToHtml; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.converter.ExcelToHtmlConverter; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hwpf.converter.PicturesManager; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.hwpf.usermodel.Picture; import org.apache.poi.hwpf.usermodel.PictureType; import org.w3c.dom.Document; public class PoiExcelToHtml { final static String path = "D:\\poi-test\\excelToHtml\\"; final static String file = "exportExcel.xls"; public static void main(String args[]) throws Exception { InputStream input=new FileInputStream(path+file); HSSFWorkbook excelBook=new HSSFWorkbook(input); ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ); excelToHtmlConverter.processWorkbook(excelBook); List pics = excelBook.getAllPictures(); if (pics != null) { for (int i = 0; i < pics.size(); i++) { Picture pic = (Picture) pics.get (i); try { pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) ); } catch (FileNotFoundException e) { e.printStackTrace(); } } } Document htmlDocument =excelToHtmlConverter.getDocument(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DOMSource domSource = new DOMSource (htmlDocument); StreamResult streamResult = new StreamResult (outStream); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty (OutputKeys.INDENT, "yes"); serializer.setOutputProperty (OutputKeys.METHOD, "html"); serializer.transform (domSource, streamResult); outStream.close(); String content = new String (outStream.toByteArray() ); FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8"); } }
###ppt转html
其实只是ppt转图片,有了图片后放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程。package pptToImg; import java.awt.Dimension; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import org.apache.poi.hslf.model.TextRun; import org.apache.poi.hslf.record.Slide; import org.apache.poi.hslf.usermodel.RichTextRun; import org.apache.poi.hslf.usermodel.SlideShow; public class PPTtoImage { public static void main(String[] args) { // 读入PPT文件 File file = new File("D:/poi-test/pptToImg/test.ppt"); doPPTtoImage(file); } public static boolean doPPTtoImage(File file) { boolean isppt = checkFile(file); if (!isppt) { System.out.println("The image you specify don't exit!"); return false; } try { FileInputStream is = new FileInputStream(file); SlideShow ppt = new SlideShow(is); is.close(); Dimension pgsize = ppt.getPageSize(); org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides(); for (int i = 0; i < slide.length; i++) { System.out.print("第" + i + "页。"); TextRun[] truns = slide[i].getTextRuns(); for ( int k=0;k<truns.length;k++){ RichTextRun[] rtruns = truns[k].getRichTextRuns(); for(int l=0;l<rtruns.length;l++){ int index = rtruns[l].getFontIndex(); String name = rtruns[l].getFontName(); rtruns[l].setFontIndex(1); rtruns[l].setFontName("宋体"); // System.out.println(rtruns[l].getText()); } } BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); graphics.setPaint(Color.BLUE); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); slide[i].draw(graphics); // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径 FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg"); javax.imageio.ImageIO.write(img, "jpeg", out); out.close(); } System.out.println("success!!"); return true; } catch (FileNotFoundException e) { System.out.println(e); // System.out.println("Can't find the image!"); } catch (IOException e) { } return false; } // function 检查文件是否为PPT public static boolean checkFile(File file) { boolean isppt = false; String filename = file.getName(); String suffixname = null; if (filename != null && filename.indexOf(".") != -1) { suffixname = filename.substring(filename.indexOf(".")); if (suffixname.equals(".ppt")) { isppt = true; } return isppt; } else { return isppt; } } }
ppt转图片有个缺陷,就是ppt里不是宋体的字有些可能会变成框框。
以上都需要引入poi的jar包。
要实现在线预览,只需把转换得到的html在新标签页打开或者镶嵌到某块区域就可以展现了。 -
poi
2020-08-27 17:14:37poi 两种模式 1.用户模式 一次性加载excel(xml文档以一棵DOM树的形式存放在内存中) 数据量大会OOM 2.SAX模式(XSSF and SAX(event API)) 逐行读取xml解析(excel有03和07两种版本,两个版本数据存储方式截然不同,...poi 两种模式
1.用户模式
一次性加载excel(xml文档以一棵DOM树的形式存放在内存中) 数据量大会OOM
2.SAX模式(XSSF and SAX(event API))
逐行读取xml解析(excel有03和07两种版本,两个版本数据存储方式截然不同,sax解析方式也各不一样 api复杂不利于实现)
EasyExcel
官网
https://www.yuque.com/easyexcel/doc/easyexcel
原理
1.对poi的封装和改版
2.文件解压文件读取通过文件形式(通过磁盘可以减少内存的使用)
3.采用sax模式一行一行解析,并将一行的解析结果以观察者的模式通知处理
4.抛弃不重要的数据(样式,字体,宽度) -
POI
2011-05-01 17:42:00package poi; import java.io.FileOutputStream;import java.util.Calendar;import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import...使用这套API操作Excel时,将对Excel进行全程锁定,所以不能有其他程序访问同一文件.
package poi;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.HSSFColor;
public class App {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("d:/poi.xls");
// 建立工作空间
HSSFWorkbook wb = new HSSFWorkbook();
// 创建工作表
HSSFSheet sheet = wb.createSheet("first Sheet");
wb.createSheet("second Sheet");
// 创建行
HSSFRow row = sheet.createRow(0);
// 创建单元格
HSSFCell cell = row.createCell(0);
// 设置不同的值进行比较
cell.setCellValue(true);// boolean
row.createCell(1).setCellValue(Calendar.getInstance());// 日历类型
row.createCell(2).setCellValue(new Date());// date类型
row.createCell(3).setCellValue(123456789.987654321);// double
String str = "sadfasdfsadfsadfsdddddddddddffffffffffffffffdsadf";
row.createCell(4).setCellValue(new HSSFRichTextString(str));// String
// 格式化单元格数据
HSSFCellStyle style = wb.createCellStyle();// 创建样式对象
HSSFDataFormat format = wb.createDataFormat();// 创建数据格式对象
style.setDataFormat(format.getFormat("yyyy-MM-dd hh:mm:ss"));
row.getCell(1).setCellStyle(style);
row.getCell(2).setCellStyle(style);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,###.0000"));
row.getCell(3).setCellStyle(style);
// 设置列宽,单位int:是点的1/20
sheet.setColumnWidth(1, 5000);
sheet.autoSizeColumn((short) 2);// 自动列宽
sheet.autoSizeColumn((short) 4);
// 设置文本的对齐方式
row = sheet.createRow(1);
row.createCell(0).setCellValue(new HSSFRichTextString("左上"));
row.createCell(1).setCellValue(new HSSFRichTextString("中中"));
row.createCell(2).setCellValue(new HSSFRichTextString("右下"));
// #左上
style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 水平左
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 水平左
row.getCell(0).setCellStyle(style);
// #中中
style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
row.getCell(1).setCellStyle(style);
// #左上
style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_BOTTOM);
row.getCell(2).setCellStyle(style);
// 行高
row.setHeight((short) 2000);
// 字体颜色和大小
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) 30);// 字体高度
font.setItalic(true);// 斜体
font.setColor(HSSFColor.RED.index);// 字体颜色
style = row.getCell(0).getCellStyle();
style.setFont(font);// 为单元格样式应用字体
sheet.setColumnWidth(0, (short) 5000);
// 设置旋转
style.setRotation((short) 60);
// 设置边框样式
row = sheet.createRow(2);
cell = row.createCell(0);
style = wb.createCellStyle();
style.setTopBorderColor(HSSFColor.RED.index);// 上边框
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT);
cell.setCellStyle(style);
// 计算列
row = sheet.createRow(3);
row.createCell(0).setCellValue(12);
row.createCell(1).setCellValue(13);
row.createCell(2).setCellValue(14);
cell = row.createCell(3);
cell.setCellFormula("average(A4:C4)");
row = sheet.createRow(4);
row.createCell(0).setCellValue(22);
row.createCell(1).setCellValue(23);
row.createCell(2).setCellValue(24);
cell = row.createCell(3);
cell.setCellFormula("sum(A4:C5)");
// 整体移动行
// sheet.shiftRows(2, 4, -1);
// 拆分窗格
// 1000:x轴拆分距离 2000:y轴拆分距离
// 1:右侧窗格开始显示的列的索引数 2:下策窗口开始显示的行的索引的数
// 2:哪个面板去激活
// sheet.createSplitPane(1000, 2000, 1, 2, 2);
// 冻结窗格
// 1:冻结的列数 2:冻结行数 3:右侧窗格从第几列开始显示 4:下侧窗格从第几行开始显示
// sheet.createFreezePane(1, 2, 3, 4);
wb.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
-
Apache POI与Alibaba EasyExcel 的使用
2020-09-30 14:04:20Apache POI 与 Alibaba EasyExcel Apache POI <dependencies> <!-- xls(03) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</...Apache POI 与 Alibaba EasyExcel 的使用
- Apache POI
<dependencies> <!-- xls(03) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <!-- xls(07) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <!-- 日期格式化工具 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
- 测试写(03版)
String Path = "D:\\data\\"; @Test public void testWrite03() throws Exception { // 创建工作簿对象 03 Workbook workbook = new HSSFWorkbook(); // 创建一个工作表 Sheet sheet0 = workbook.createSheet("BLU测试表"); // 创建一行 Row row0 = sheet0.createRow(0); // 创建一个单元格 Cell cell00 = row0.createCell(0); cell00.setCellValue("编号"); Cell cell01 = row0.createCell(1); cell01.setCellValue("姓名"); Row row1 = sheet0.createRow(1); Cell cell10 = row1.createCell(0); cell10.setCellValue(1); Cell cell11 = row1.createCell(1); cell11.setCellValue("BLU"); Cell cell12 = row1.createCell(2); String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss"); cell12.setCellValue(time); FileOutputStream fos = new FileOutputStream(Path + "test03.xls"); workbook.write(fos); fos.close(); System.out.println("文件生成完毕"); }
- 测试写(07版)
String Path = "D:\\data\\"; @Test public void testWrite07() throws Exception { Workbook workbook = new XSSFWorkbook(); Sheet sheet0 = workbook.createSheet("BLU测试表"); Row row0 = sheet0.createRow(0); Cell cell00 = row0.createCell(0); cell00.setCellValue("编号"); Cell cell01 = row0.createCell(1); cell01.setCellValue("姓名"); Row row1 = sheet0.createRow(1); Cell cell10 = row1.createCell(0); cell10.setCellValue(1); Cell cell11 = row1.createCell(1); cell11.setCellValue("BLU"); Cell cell12 = row1.createCell(2); String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss"); cell12.setCellValue(time); FileOutputStream fos = new FileOutputStream(Path + "test07.xlsx"); workbook.write(fos); fos.close(); System.out.println("文件生成完毕"); }
- 测试大数据写入(03版)
String Path = "D:\\data\\"; /** * 65536行数据耗时:2.815s * 最多只能创建65536行 */ @Test public void testWrite03BigData() throws Exception { long begin = System.currentTimeMillis(); HSSFWorkbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(); for (int rowNum = 0; rowNum < 65536; rowNum++) { Row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < 10; cellNum++) { Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } System.out.println("over"); FileOutputStream fos = new FileOutputStream(Path + "testWrite03BigData.xls"); workbook.write(fos); fos.close(); long end = System.currentTimeMillis(); System.out.println((double) (end - begin) / 1000); }
- 测试大数据写入(07版)
String Path = "D:\\data\\"; /** * 65536行数据耗时6.843s * 10万行数据耗时13.028s * 内存占用大 */ @Test public void testWrite07BigData() throws Exception { long begin = System.currentTimeMillis(); XSSFWorkbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(); for (int rowNum = 0; rowNum < 100000; rowNum++) { Row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < 10; cellNum++) { Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } System.out.println("over"); FileOutputStream fos = new FileOutputStream(Path + "testWrite07BigData.xlsx"); workbook.write(fos); fos.close(); long end = System.currentTimeMillis(); System.out.println((double) (end - begin) / 1000); }
- 使用 SXSSFWorkbook 测试大数据写入
String Path = "D:\\data\\"; /** * 10万行数据耗时1.916s */ @Test public void testWrite07BigDataS() throws Exception { long begin = System.currentTimeMillis(); SXSSFWorkbook workbook = new SXSSFWorkbook(); Sheet sheet = workbook.createSheet(); for (int rowNum = 0; rowNum < 100000; rowNum++) { Row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < 10; cellNum++) { Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } System.out.println("over"); FileOutputStream fos = new FileOutputStream(Path + "testWrite07BigDataS.xlsx"); workbook.write(fos); fos.close(); // 清除临时文件 workbook.dispose(); long end = System.currentTimeMillis(); System.out.println((double) (end - begin) / 1000); }
- 测试读(03版)
String Path = "D:\\data\\"; @Test public void testRead03() throws Exception { FileInputStream fis = new FileInputStream(Path + "test03.xls"); Workbook workbook = new HSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(1); Cell cell0 = row.getCell(0); double value0 = cell0.getNumericCellValue(); System.out.println(value0); Cell cell1 = row.getCell(1); String value1 = cell1.getStringCellValue(); System.out.println(value1); fis.close(); }
1.0 BLU
- 测试读(07版)
String Path = "D:\\data\\"; @Test public void testRead07() throws Exception { FileInputStream fis = new FileInputStream(Path + "test07.xlsx"); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(1); Cell cell0 = row.getCell(0); double value0 = cell0.getNumericCellValue(); System.out.println(value0); Cell cell1 = row.getCell(1); String value1 = cell1.getStringCellValue(); System.out.println(value1); fis.close(); }
1.0 BLU
- 根据数据类型读取的示例:
BLU.xls文件:
String Path = "D:\\data\\"; @Test public void testCellType() throws Exception { FileInputStream fis = new FileInputStream(Path + "BLU.xls"); Workbook workbook = new HSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); Row rowTitle = sheet.getRow(0); if (rowTitle != null) { int cellCount = rowTitle.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { Cell cell = rowTitle.getCell(cellNum); if (cell != null) { String cellValue = cell.getStringCellValue(); System.out.print(cellValue + " | "); } } } System.out.println(); int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowNum = 1; rowNum < rowCount; rowNum++) { Row rowData = sheet.getRow(rowNum); if (rowData != null) { int cellCount = rowData.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { Cell cell = rowData.getCell(cellNum); if (cell != null) { int cellType = cell.getCellType(); switch (cellType) { case HSSFCell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.print(String.valueOf(cell.getBooleanCellValue())); break; case HSSFCell.CELL_TYPE_BLANK: break; case HSSFCell.CELL_TYPE_NUMERIC: if(HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); String s = new DateTime(date).toString("yyyy-MM-dd"); System.out.print(s); }else { cell.setCellType(HSSFCell.CELL_TYPE_STRING); System.out.print(cell.toString()); } break; case HSSFCell.CELL_TYPE_ERROR: break; } System.out.print(" | "); } } System.out.println(); } } fis.close(); }
手机号 | 日期 | 订单号 | 商品编号 | 商品名称 | 价格 | 销售数量 | 销售金额 | 已发货 | 15651776666 | 2020-09-30 | 000001 | 1 | 蒙牛 | 65.5 | 1 | 65.5 | true | 15651776666 | 2020-10-01 | 000002 | 2 | 脑白金 | 100 | 10 | 1000 | false |
- 读取计算函数的示例:
func.xls文件:
String Path = "D:\\data\\"; @Test public void testFormula() throws Exception { FileInputStream fis = new FileInputStream(Path + "func.xls"); Workbook workbook = new HSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(4); Cell cell = row.getCell(0); FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook); int cellType = cell.getCellType(); switch(cellType) { case Cell.CELL_TYPE_FORMULA: String formula = cell.getCellFormula(); System.out.println(formula); CellValue evaluate = formulaEvaluator.evaluate(cell); String cellValue = evaluate.formatAsString(); System.out.println(cellValue); break; } }
SUM(A2:A4) 600.0
- Alibaba EasyExcel
<dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.0-beta2</version> </dependency> <!-- 日期格式化工具 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
- 实体类:
package com.blu.easy; import java.util.Date; import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data; @Data public class DemoData { @ExcelProperty("字符串标题") private String string; @ExcelProperty("日期标题") private Date date; @ExcelProperty("数字标题") private Double doubleData; /** * 忽略这个字段 */ @ExcelIgnore private String ignore; }
- 监听器:
package com.blu.easy; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.fastjson.JSON; public class DemoDataListener extends AnalysisEventListener<DemoData> { private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class); private static final int BATCH_COUNT = 5; List<DemoData> list = new ArrayList<DemoData>(); private DemoDAO demoDAO; public DemoDataListener() { demoDAO = new DemoDAO(); } public DemoDataListener(DemoDAO demoDAO) { this.demoDAO = demoDAO; } @Override public void invoke(DemoData data, AnalysisContext context) { System.out.println(JSON.toJSONString(data)); list.add(data); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveData(); // 存储完成清理 list list.clear(); } } /** * 所有数据解析完成了 都会来调用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveData(); LOGGER.info("所有数据解析完成!"); } /** * 加上存储数据库 */ private void saveData() { LOGGER.info("{}条数据,开始存储数据库!", list.size()); demoDAO.save(list); LOGGER.info("存储数据库成功!"); } }
- DAO:
package com.blu.easy; import java.util.List; /** * 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。 **/ public class DemoDAO { public void save(List<DemoData> list) { // 持久化操作 // 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入 } }
- 测试:
package com.blu.easy; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import com.alibaba.excel.EasyExcel; public class EasyTest { String Path = "D:\\data\\"; private List<DemoData> data() { List<DemoData> list = new ArrayList<DemoData>(); for (int i = 0; i < 10; i++) { DemoData data = new DemoData(); data.setString("字符串" + i); data.setDate(new Date()); data.setDoubleData(0.56); list.add(data); } return list; } /** * 最简单的写 */ @Test public void simpleWrite() { String fileName = Path + "easyTest.xlsx"; EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data()); } /** * 最简单的读 */ @Test public void simpleRead() { // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去 String fileName = Path + "easyTest.xlsx"; // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭 EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead(); } }
写入结果:
读取结果:{"date":1601434567000,"doubleData":0.56,"string":"字符串0"} {"date":1601434567000,"doubleData":0.56,"string":"字符串1"} {"date":1601434567000,"doubleData":0.56,"string":"字符串2"} {"date":1601434567000,"doubleData":0.56,"string":"字符串3"} {"date":1601434567000,"doubleData":0.56,"string":"字符串4"} {"date":1601434567000,"doubleData":0.56,"string":"字符串5"} {"date":1601434567000,"doubleData":0.56,"string":"字符串6"} {"date":1601434567000,"doubleData":0.56,"string":"字符串7"} {"date":1601434567000,"doubleData":0.56,"string":"字符串8"} {"date":1601434567000,"doubleData":0.56,"string":"字符串9"}
-
Apache POI使用详解
2017-06-05 20:11:35一 :简介开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中,操作Excel目前有两个框架,一个是apache 的poi, 另一个是 Java Excel Apache POI 简介是用Java编写的免费开源的跨平台的 Java API,... -
poi3.9
2013-01-27 22:36:06poi3.9 -
poi的3.17版本问题
2020-04-01 12:01:32网上很多版本对于poi中样式中样式设置都是poi之前的操作,在poi3.17版本中并不能直接使用 (1)单元格样式 在poi导出设置单元格样式的居中问题时候,网上大部分的操作代码如下: XSSFCellStyle cellStyle = wb.... -
java使用poi读取doc和docx文件
2016-07-22 10:53:02这几天在学习java io流的东西,有一个网友... 于是在网上搜寻了一阵之后才发现原来doc文档和excel一样不能用普通的io流的方法来读取,而是也需要用poi,于是进行了一番尝试后,终于以正确的编码格式读取了这个doc文件。 -
JAVA使用POI读取EXCEL文件的简单model
2017-05-23 14:42:03[java] view plain copy print?packagepoi;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.util.Iterator;importorg.apache.poi.hssf.usermodel.HS -
如何下载全国的POI数据,如何获取全国的POI数据,poi数据搜索,高德poi获取,poi数据分析,poi免费数据,城市规划...
2020-03-01 22:55:41最近朋友写论文,让我帮他弄poi数据,偶然间发现一个小程序,进而获取了全国的poi数据 教程如下: Step1 打开微信,扫码使用小程序 注意: 1,它会要求填写手机号和邮箱 ps:这里最重要的是邮箱,会收到一封搜索poi数据结果的... -
提高POI 读写效率
2018-02-01 11:14:58POI -
java poi导出Excel表格超大数据量解决方案
2016-07-02 10:59:43Java实现导出excel表格功能,大部分都会使用apache poi, apache poi API 地址 -
Java 操作Excel poi读写excel
2018-10-21 10:45:46Java 操作Excel poi读写excel,excel导入导出(精简版) 1.所需jar包 下载地址:https://download.csdn.net/download/u014646662/10734734 2.源码 写操作(excel导出) package cn.com.tengen.excel; import... -
poi简介与简单使用
2019-03-09 17:22:30POI是Apache软件基金会用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的... -
Java POI 导入导出Excel简单实例源代码
2014-08-28 16:25:39Java POI 导入导出Excel简单实例源代码 该源代码的jar包,参见以下博文附录截图 Java POI导出EXCEL经典实现 Java导出Excel弹出下载框 http://blog.csdn.net/evangel_z/article/details/7332535 web页面导出Excel... -
POI3.17与POI旧版本对比,方便POI升级jar包修改
2020-04-30 16:15:42POI3.17与POI旧版本对比,方便POI升级jar包修改颜色定义变化获取单元格格式设置单元格格式设置单元格垂直居中样式设置边框合并单元格设置字体加粗 最近使用EasyExcel写导入导出Excel,需要POI版本是3.17,之前是3.9... -
【POI框架实战】——POI导出Excel时设置单元格类型为数值类型
2015-11-17 19:04:12最近做的一个ITFIN的项目中,导出的数据中有文本格式...然后往单元格中存放数据的时候要设置数据的格式为double类型,如果查看poi的源码HSSFCell.java会发现设置数据的方法如下,所以用setCellValue(double)方法即可。 -
POI配置
2019-04-14 00:05:23/xml配置文件/其他配置/POI配置/POI配置.txt1、导包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency> ... -
使用Java代码(POI)读写 Excel
2020-01-07 19:49:59使用Java代码(POI)读写 Excel,这篇博客给出了实现逻辑并有完整的代码实现。 -
POI教程
2019-01-15 11:08:19POI报表 --用POI与Excel交互 AURISOFT 第一章 POI简介 --Jakata Poi HSSF:纯java的Excel解决方案 在我们实际的开发中,表现层的解决方案虽然有多样,但是IE浏览器已成为最多人使用的浏览器,因为大家都用... -
Java POI Excel读取
2017-12-12 11:54:01POI版本3.15 pom文件 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <... -
POI 题解
2016-09-01 15:59:48从2015年开始往前一点一点做的POI题解汇总(全中文!!!): POI2015 POI2014 POI2013 POI2012 POI2011 -
poi内存溢出解决办法
2018-01-03 11:41:55poi -
POI 技术实战
2018-08-14 00:43:43POI 技术如何实现对 Word 和 Excel 的读写操作?POI 技术相对其他同类型技术的优劣势又是哪些?怎样实现复杂的 Excel 读写操作?POI 对于 Word 和 Excel 有足够友好吗?这个 Chat,带领大家使用免费却实用的 POI ... -
POI复制行,POI复制列
2018-06-07 16:56:18package ...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... -
easy poi 与poi 冲突解决方案
2019-12-25 11:45:23在1个项目中使用easy poi 是不错的选择,不过会与项目中的poi冲突,这就需要解决jar包冲突的问题,在网上找了很多解决方案吗,但是并没有找到。方便日后查阅。希望帮助大家。 <!-- Excel 导出 --> <... -
poi下载
2018-07-26 18:35:09当前很多网站都提供了POI的下载界面,但是一般都需要KEY来实现。然而每个KEY(正常是个人请求的)一般每天配额度也就1000条,这对于想要大量POI数据的需求获取而言,简直是杯水车薪。 餐饮、宾馆、购物、生活服务、... -
POI如何读取树形结构的excel文件?并产生树形结构
2020-07-31 17:42:56import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org... -
使用poi来导入具有合并单元格的excel表格
2020-04-01 11:38:33pom依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> &l... -
poi api
2007-11-28 10:46:41poi能用java生成几乎所有office文档。 poi api doc文档 版本:2.5 格式:chm 来源:自制 老四出手,必是精品。
-
WPF上位机数据采集与监控系统零基础实战
-
API HOOK拦截指定进程发送和接收的网络数据包.zip
-
【2021】Python3+Selenium3自动化测试(不含框架)
-
转行做IT-第7章 数组
-
Unity游戏开发之数字华容道
-
还没富的人们,学计算机吧.这是我对你们的忠告
-
【数据分析-随到随学】机器学习模型及应用
-
python数据分析基础
-
信息系统项目管理师考前必做650题.pdf
-
前端优化 - externals 实现运行时加载依赖
-
Linux系统编程篇—进程(六)system函数、popen函数
-
PHP支付宝微信支付配置教程
-
【数据分析-随到随学】Python数据获取
-
vue-cli3脚手架创建项目
-
旧版 FoxitReade
-
Selenium3分布式与虚拟化
-
subplot_std.m
-
《零起点TF与量化交易》源码.rar
-
Java基础内部类.xmind文件
-
【数据分析-随到随学】Python语法强化与数据处理