---
title: "POI将html语句写入Excel，并保留格式"
author: "easonfans"
date: "2010-10-08T21:39:42Z"
tags: []
categories: ["编程语言"]
slug: "poi-html-excel"
draft: false
lastmod: "2010-10-08T21:39:42Z"
id: 779012
url: "https://easonfans.iteye.com/blog/779012"
---

嗯，最近在做单位内部使用的一个系统

其中在前台使用FCKeditor编辑html，并将编辑的html文本保存在excel中

这里涉及到两个问题

一是：要将数据库中保存的html中的html标签去除

二是：对于语句中的换行，使用poi是如何保持换行

 

查阅了相关资料，解决的方法如下：

一：

使用正则表达式去除html语句中的html标签

 

```
public static String splitAndFilterString(String input) {  
        if (input == null || input.trim().equals("")) {  
            return "";  
        }  
        // 去掉所有html元素,  
        String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(  
                "<[^>]*>", "");  
        str = str.replaceAll("[(/>)<]", "");  
        return str;  
 }  
```

 

 相关来源：

[http://www.iteye.com/topic/217508](http://www.iteye.com/topic/217508)

经使用可行，但是很多人说这么做很暴力，会删除如内容用&lt;1&gt;&lt;2&gt;&lt;3&gt;这样的形式来作为步骤的标示

并修改为：

 

```
// 去掉所有html元素,     
String str = input.replaceAll("<[a-zA-Z]+[1-9]?[^><]*>", "")  
                  .replaceAll("</[a-zA-Z]+[1-9]?>", "");  
```

 

 也可行！

二：

使用POI在excel中输入换行时候，需要设置cell的样式和在字符串中加入"\\"------"\\r\\n "HSSFRichTextString重新封装一下字符串。

具体的代码如下：

```
//首先设置cell的style
HSSFCellStyle cellStyle=workbook.createCellStyle();     
cellStyle.setWrapText(true);     
cell.setCellStyle(cellStyle); 
```

 接下来修改你要写入excel的字符串

```
HSSFCell cell = row.createCell((short)0);  
cell.setCellStyle(cellStyle);                           
cell.setCellValue(new HSSFRichTextString("hello\r\n world!"));  
```

 就可以了

 

相关链接：[http://www.iteye.com/topic/425524](http://www.iteye.com/topic/425524)

感谢：bevis.cn和liuwei1981