POI操作Office导出Html文档

更新日期:2015-10-13 对Excel中的公式不能执行的bug修复,增加对系统的判断,window下实现gkb2312,在linux系统中由于SUSE支持中文比较费劲,所以实现UTF-8

package com.hrhx.mcc.util;

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.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
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.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 PoiToHtmlUtil {
	/**
	 * 
	 * @param path 所在的文件夹
	 * @param inFileName 输入Word文档
	 * @param outFileName 输出Html文档
	 * @throws Throwable
	 */
	public static void wordToHtml(String path,String inFileName,String outFileName) throws Throwable {
		
		InputStream input = new FileInputStream(path + inFileName);
		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<Picture> 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, "gb2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();

		String content = new String(outStream.toByteArray());

		FileUtils.write(new File(path, outFileName), content, "gb2312");
	}
	
	/**
	 * 
	 * @param path 所在的文件夹
	 * @param inFileName 输入Excel文档
	 * @param outFileName 输出Html文档
	 * @throws Throwable
	 */
	@SuppressWarnings("rawtypes")
	public static String  excelToHtml(String path,String inFileName) throws Throwable {
		
		InputStream input = new FileInputStream(path +"/"+ inFileName);
		HSSFWorkbook excelBook = new HSSFWorkbook(input);
		resetCellFormula(excelBook);
		ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		
		//去掉Excel头行
		//excelToHtmlConverter.OutputColumnHeaders = false;
		excelToHtmlConverter.setOutputColumnHeaders(false);
		//去掉Excel行号
		excelToHtmlConverter.setOutputRowNumbers(false);
		
		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();
		
		//判断操作系统是windows,还是Linux的SUSE系统
		if(isWindows()){
			serializer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
		}else{
			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());
		return content;
	}
	
	public static boolean isWindows(){
	    boolean flag = false;
	    if (System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
	    flag = true;
	    }
	    return flag;
	}
	
	/**
	 * 
	 * 重新设置单元格计算公式
	 * 
	 * */
	public static void resetCellFormula(HSSFWorkbook wb) {
		HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(wb);
		int sheetNum = wb.getNumberOfSheets();
		for (int i = 0; i < sheetNum; i++) {
			HSSFSheet sheet = wb.getSheetAt(i);
			int rows = sheet.getLastRowNum() + 1;
			for (int j = 0; j < rows; j++) {
				HSSFRow row = sheet.getRow(j);
				if (row == null)
					continue;
				int cols = row.getLastCellNum();
				for (int k = 0; k < cols; k++) {
					HSSFCell cell = row.getCell(k);
					if(cell!=null)
					    System.out.println("cell["+j+","+k+"]=:"+cell.getCellType());
					if (cell == null)
						continue;
					if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
						cell.setCellFormula(cell.getCellFormula());
						System.out.println("----公式:"+cell.getCellFormula());
						cell=e.evaluateInCell(cell);
						//System.out.println("-----------"+cell.getNumericCellValue());
					}
				}
			}
		}
	}
}


更新日期:2015-10-12 出版

package com.hrhx.mcc.util;

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.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 PoiToHtmlUtil {
	/**
	 * 
	 * @param path 所在的文件夹
	 * @param inFileName 输入Word文档
	 * @param outFileName 输出Html文档
	 * @throws Throwable
	 */
	public static void wordToHtml(String path,String inFileName,String outFileName) throws Throwable {
		
		InputStream input = new FileInputStream(path + inFileName);
		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<Picture> 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, "gb2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();

		String content = new String(outStream.toByteArray());

		FileUtils.write(new File(path, outFileName), content, "gb2312");
	}
	/**
	 * 
	 * @param path 所在的文件夹
	 * @param inFileName 输入Excel文档
	 * @param outFileName 输出Html文档
	 * @throws Throwable
	 */
	@SuppressWarnings("rawtypes")
	public static String  excelToHtml(String path,String inFileName) throws Throwable {
		
		InputStream input = new FileInputStream(path +"/"+ inFileName);
		HSSFWorkbook excelBook = new HSSFWorkbook(input);
		ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		
		//去掉Excel头行
		excelToHtmlConverter.setOutputColumnHeaders(false);
		//去掉Excel行号
		excelToHtmlConverter.setOutputRowNumbers(false);
		
		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, "gb2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		//excelToHtmlConverter.OutputColumnHeaders = false;
		serializer.transform(domSource, streamResult);
		outStream.close();

		String content = new String(outStream.toByteArray());
		//去掉Excel中的列A B C D
		//content = StringUtil.regexReplaceStr(content,"<thead>[^<]*[^d]*[^i]*[^v]*[^>]*</thead>", "");
		//去掉Excel中的行1 2 3
		//content = StringUtil.regexReplaceStr(content,"<th class=\"rownumber\">.*?</th>","<th class=\"rownumber\"></th>");
		return content;
		//FileUtils.write(new File(path, outFileName), content, "gb2312");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: Java POI 是一个用于操作 Microsoft Office 格式文件的 Java 库,包括 Word、Excel 和 PowerPoint 等文件。在 Java 中使用 POI 库可以方便地读取、修改和创建 Office 文件。 在使用 POI 导出 Word 文档时,需要先创建一个空的 Word 文档,然后向其中添加内容。可以使用 POI 提供的 XWPFDocument 类来创建 Word 文档对象,使用 XWPFParagraph 类来创建段落对象,使用 XWPFRun 类来创建文本对象。 在创建段落对象时,可以设置段落的样式,如字体、字号、颜色、对齐方式等。在创建文本对象时,可以设置文本的样式,如加粗、斜体、下划线等。 除了文本内容,还可以向 Word 文档中添加表格、图片、超链接等元素。可以使用 POI 提供的 XWPFTable 类来创建表格对象,使用 XWPFTableRow 和 XWPFTableCell 类来创建表格行和单元格对象。可以使用 XWPFParagraph 类的 addPicture 方法来添加图片,使用 XWPFHyperlink 类来添加超链接。 最后,将创建好的 Word 文档保存到本地文件系统或输出流中即可。可以使用 XWPFDocument 类的 write 方法将文档保存到文件中,使用 XWPFDocument 类的 write 方法将文档输出到输出流中。 总之,使用 Java POI 导出 Word 文档需要掌握 XWPFDocument、XWPFParagraph、XWPFRun、XWPFTable、XWPFTableRow、XWPFTableCell、XWPFHyperlink 等类的使用方法,以及如何设置样式、添加元素和保存文档。 ### 回答2: Java POI是一个流行的Java库,它提供了对微软Office格式的读取和写入支持,其中包括Word文档导出。在使用此库导出Word文档时,可以按照以下步骤进行操作: 第一步:导入所需的库文件和工具 我们需要导入Apache POI库以及相关的库文件来使用Java POI。可以从maven中央仓库中下载这些库文件,也可以通过其他方式来获取这些文件。在项目中添加所需的库文件,并在相关的类中导入这些库文件。 第二步:创建Word文档 在Java中,可以使用XWPFDocument类来创建一个空白的Word文档。在此类中,可以添加标题,正文文本,表格等内容,以构建新的Word文档。可以使用以下代码来创建一个新的Word文档。 XWPFDocument doc = new XWPFDocument(); 第三步:添加内容 在Java POI中,可以使用XWPFParagraph类来添加Word文档中的段落。可以使用此类来添加文字,图片等。以下是如何使用XWPFParagraph类来添加段落的示例代码: XWPFParagraph para = doc.createParagraph(); XWPFRun run = para.createRun(); run.setText("这是一个段落"); 可以使用XWPFTable类来添加Word文档中的表格。以下是如何使用XWPFTable类来添加表格的示例代码: XWPFTable table = doc.createTable(); XWPFTableRow row = table.getRow(0); row.getCell(0).setText("第一行第一列"); row.addNewTableCell().setText("第一行第二列"); 第四步:保存文档 完成了Word文档的创建和内容添加之后,需要将其保存到磁盘上。可以使用FileOutputStream类和XWPFDocument类的write() 方法来完成保存。以下代码片段演示了如何将文档保存到磁盘上: FileOutputStream outputStream = new FileOutputStream(new File("output.docx")); doc.write(outputStream); outputStream.close(); 总结 Java POI提供了一种通过代码来创建和编辑Word文档的方式。使用Java POI,我们可以创建空白的Word文档,向文档中添加内容,例如文字,图片和表格。最后,我们可以将文档保存到磁盘上。通过这些步骤,我们可以轻松地使用Java POI导出Word文档。 ### 回答3: Java POI是一个开源的Java库,用于处理各种Microsoft Office格式文件,包括Word文档(.docx)、Excel表格(.xlsx)和PowerPoint演示文稿(.pptx)。在Java POI中,我们可以使用XWPFDocument对象导出Word文档。 1. 导入依赖 在使用Java POI库之前,首先必须要引入相应的依赖包。我们需要使用以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Word文档 我们可以使用XWPFDocument类创建一个新的Word文档。默认情况下,文档中没有任何内容: ``` XWPFDocument document = new XWPFDocument(); ``` 3. 添加标题 添加标题可以使用XWPFParagraph和XWPFRun类。XWPFParagraph用于存储段落内容,而XWPFRun用于添加样式。以下是一个添加标题的示例代码: ``` XWPFParagraph titlePara = document.createParagraph(); XWPFRun titleRun = titlePara.createRun(); titleRun.setBold(true); titleRun.setFontSize(16); titleRun.setText("这是一个标题"); ``` 4. 添加正文 添加正文和添加标题类似,只不过我们可以在添加文本之前使用setBold、setItalic、setUnderline等方法设置样式。以下是添加正文的示例代码: ``` XWPFParagraph contentPara = document.createParagraph(); XWPFRun contentRun = contentPara.createRun(); contentRun.setFontSize(12); contentRun.setText("这是一个正文"); ``` 5. 添加图片 在Word文档中添加图片可以使用XWPFRun类的addPicture方法。需要注意的是,图片必须先被转换为byte数组。以下是添加图片的示例代码: ``` // 读取图片文件 FileInputStream fis = new FileInputStream("path/to/image.png"); byte[] imageData = IOUtils.toByteArray(fis); fis.close(); // 添加图片 XWPFParagraph imagePara = document.createParagraph(); XWPFRun imageRun = imagePara.createRun(); imageRun.addPicture(new ByteArrayInputStream(imageData), XWPFDocument.PICTURE_TYPE_PNG, "image.png", Units.toEMU(300), Units.toEMU(200)); ``` 6. 保存文档 在完成文档的内容添加后,我们可以将文档保存到指定的文件中。以下是保存文档的示例代码: ``` OutputStream os = new FileOutputStream("path/to/output.docx"); document.write(os); os.close(); document.close(); ``` 以上就是使用Java POI导出Word文档的详细步骤。通过使用Java POI,我们可以方便地创建和编辑Word文档,并将其保存为docx格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值