基于POI的两个JAVA操作Office工具类
来源:互联网 发布:红痘印 知乎 编辑:程序博客网 时间:2024/06/14 02:34
一个简单的Excel生成类
import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.List;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;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.ss.usermodel.HorizontalAlignment;import org.apache.poi.ss.usermodel.VerticalAlignment;public class ExcelCreator { private ExcelCreator() { } private static final int FIRST_TABLE_ROW_NUMBER = 0; /** * 生成的Excel文件的文件名 */ private String fileName = System.currentTimeMillis() + ""; /** * 如果是输出到本地的话,这个路径将会记录输出到本地的哪一个路径 */ private String fileSavePath; /** * 工作表的表名 */ private String sheetName = "表1"; /** * 每一列数据的表头信息 */ private String[] headers; /** * 每一行的数据 */ private List<List<String>> datas; /** * 每一列的宽度 */ private short[] colWidths; /** * 是否水平居中 */ private boolean isHorizontalCENTER = false; /** * 是否垂直居中 */ private boolean isVerticalCENTER = false; /** * 是否自动换行 */ private boolean isWrapText = true; public static class Builder { /** * 生成的Excel文件的文件名 */ private String fileName = System.currentTimeMillis() + ""; /** * 如果是输出到本地的话,这个路径将会记录输出到本地的哪一个路径 */ private String fileSavePath; /** * 工作表的表名 */ private String sheetName = "表1"; /** * 每一列数据的表头信息 */ private String[] headers; /** * 每一行的数据 */ private List<List<String>> datas; /** * 每一列的宽度 */ private short[] colWidths; /** * 是否水平居中 */ private boolean isHorizontalCENTER = false; /** * 是否垂直居中 */ private boolean isVerticalCENTER = false; /** * 是否自动换行 */ private boolean isWrapText = true; public ExcelCreator bulid() throws FileNotFoundException { if (fileSavePath == null || fileSavePath.isEmpty()) { throw new FileNotFoundException("文件保存的根目录不能为空"); } ExcelCreator creator = new ExcelCreator(); creator.fileName = fileName; creator.fileSavePath = fileSavePath; creator.sheetName = sheetName; creator.headers = headers; creator.datas = datas; creator.colWidths = colWidths; creator.isHorizontalCENTER = isHorizontalCENTER; creator.isVerticalCENTER = isVerticalCENTER; creator.isWrapText = isWrapText; return creator; } public Builder fileName(String fileName) { this.fileName = fileName; return this; } public Builder fileSavePath(String fileSavePath) { this.fileSavePath = fileSavePath; return this; } public Builder sheetName(String sheetName) { this.sheetName = sheetName; return this; } public Builder headers(String[] headers) { this.headers = headers; return this; } public Builder datas(List<List<String>> datas) { this.datas = datas; return this; } public Builder colWidths(short[] colWidths) { this.colWidths = colWidths; return this; } public Builder isHorizontalCENTER(boolean isHorizontalCENTER) { this.isHorizontalCENTER = isHorizontalCENTER; return this; } public Builder isVerticalCENTER(boolean isVerticalCENTER) { this.isVerticalCENTER = isVerticalCENTER; return this; } public Builder isWrapText(boolean isWrapText) { this.isWrapText = isWrapText; return this; } } public void create() throws IOException { // 生成excel HSSFWorkbook wb = makeExcel(); // 设置输出流 FileOutputStream fileOut = new FileOutputStream(fileSavePath + File.separator + fileName + ".xls"); writeToStream(wb, fileOut); } public void create(HttpServletResponse response) throws IOException { // 生成excel HSSFWorkbook wb = makeExcel(); // 设置输出流 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=student.xls"); writeToStream(wb, response.getOutputStream()); } private HSSFWorkbook makeExcel() { HSSFWorkbook wb = new HSSFWorkbook();// 创建Excel工作簿对象 HSSFSheet sheet = wb.createSheet(sheetName);// 创建Excel工作表对象 HSSFRow tableHeadRow = sheet.createRow(FIRST_TABLE_ROW_NUMBER); // 创建Excel工作表的行 if (colWidths != null) { // 设置每行宽度 for (int i = 0; i < colWidths.length; i++) { sheet.setColumnWidth(i, colWidths[i] * 256); } } HSSFCellStyle cellStyle = createCellStyle(wb); HSSFCell headCell = null; // 创建表头 for (int i = 0; i < headers.length; i++) { headCell = tableHeadRow.createCell(i); headCell.setCellStyle(cellStyle); // 创建Excel工作表指定行的单元格 headCell.setCellValue(headers[i]); } // 设置每一行的数据 HSSFRow dataRow = null; List<String> rowDatas = null; HSSFCell dataCell = null; int dataRowNumber = FIRST_TABLE_ROW_NUMBER + 1; for (int dataNumber = 0; dataNumber < datas.size(); dataNumber++,dataRowNumber++) { dataRow = sheet.createRow(dataRowNumber); rowDatas = datas.get(dataNumber); for (int i = 0; i < rowDatas.size(); i++) { dataCell = dataRow.createCell(i); dataCell.setCellStyle(cellStyle); dataCell.setCellValue(rowDatas.get(i)); } } return wb; } private HSSFCellStyle createCellStyle(HSSFWorkbook wb) { HSSFCellStyle cellStyle = wb.createCellStyle();// 创建单元格样式 if (isHorizontalCENTER) { cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中 } if (isVerticalCENTER) { cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中 } if (isWrapText) { cellStyle.setWrapText(true); } return cellStyle; } private void writeToStream(HSSFWorkbook wb, OutputStream outputStream) throws IOException { wb.write(outputStream); outputStream.flush(); wb.close(); }}
Word,excel转Html的工具类
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.io.PrintWriter;import java.util.List;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.apache.poi.hssf.converter.ExcelToHtmlConverter;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 OfficeUtils {/** * 将Excel文档转换为一个html页面 * * @param inputPath * 本地文件读取的路径加文件名,如:C:\\1.xls * @param outputPath * 本地文件输出的路径加文件名,如:C:\\1.xls * @throws Exception */public static void excel2Html(final String inputPath,final String outputPath) throws Exception {ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());@SuppressWarnings("static-access")Document htmlDocument = converter.process(new File(inputPath));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, "iso-8859-1");serializer.setOutputProperty(OutputKeys.INDENT, "yes");serializer.setOutputProperty(OutputKeys.METHOD, "html");serializer.transform(domSource, streamResult);outStream.close();String content = new String(outStream.toByteArray());FileOutputStream outputStream = new FileOutputStream(outputPath);PrintWriter pw = new PrintWriter(outputStream);pw.write(content);pw.close();}/** * 将一个Word文档转换为一个html页面 * * @param inputFilePath * 想要读取的文件所在文件夹的路径,如:C:\\ * @param inputFileName * 想要读取的文件名字,如:1.xls * @param outputFilePath * 准备写出的文件所在文件夹的路径,如:C:\\ * @param outputFileName * 准备写出的文件名字,如:1.xls * @throws IOException * @throws ParserConfigurationException * @throws TransformerException */public static void word2Html(final String inputFilePath,final String inputFileName, final String outputFilePath,final String outputFileName) throws IOException,ParserConfigurationException, TransformerException {InputStream input = new FileInputStream(inputFilePath + inputFileName);HWPFDocument wordDocument = new HWPFDocument(input);WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());wordToHtmlConverter.setPicturesManager(new PicturesManager() {@Overridepublic String savePicture(byte[] content, PictureType pictureType,String suggestedName, float widthInches, float heightInches) {return suggestedName;}});wordToHtmlConverter.processDocument(wordDocument);List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();if (pics != null) {for (int i = 0; i < pics.size(); i++) {Picture pic = pics.get(i);try {pic.writeImageContent(new FileOutputStream(inputFilePath+ 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());FileOutputStream outputStream = new FileOutputStream(outputFilePath+ outputFileName);PrintWriter pw = new PrintWriter(outputStream);pw.write(content);pw.close();}}
pom.xml配置:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.15</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.15</version></dependency>
1 0
- 基于POI的两个JAVA操作Office工具类
- 操作office的POI
- 操作Excel工具类(基于Apache的POI类库)
- 操作Excel工具类之基于Apache的POI类库
- Java基于POI读取Excel工具类
- java 工具类 excel 基于poi
- 一步一步学POI(java操作office类)1
- java基于poi快速操作Excel的工具Excel4J v2.0.0
- Java操作Microsoft Office(Excel) Apache POI
- 基于poi的Excel工具类修订版
- poi操作office文档
- POI操作office
- Apache POI (JAVA处理Office文档的类库)
- Apache POI (JAVA处理Office文档的类库)
- Apache POI (JAVA处理Office文档的类库)
- POI,Office文档的Java处理包
- JAVA语言工具类封装-基于poi的excel导出功能
- JAVA语言工具类封装-基于poi的excel导出功能
- java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
- Android Studio常用代码快捷方式
- MFC _GDI
- VM虚拟机下搭建Linux C++开发环境
- 224 mysql 设置远程连接权限
- 基于POI的两个JAVA操作Office工具类
- 如何防止sql注入
- Android实用技巧.视图技巧(二)
- 第十三章:字符串(下)
- kafka文档(14)----0.10.1-Document-文档(6)-configures-Kafka Connect配置信息
- 表单的验证
- AngularJS简介
- 网络中出现TCP、UDP粘包、分包的两点解决办法
- 使用Autofac做类的增强