java html转excel,保留原有带格式
时间: 2024-01-01 08:05:09 浏览: 87
您可以使用 Apache POI 库来将 HTML 文件转换为 Excel 文件,并保留原有的格式。以下是一个简单的示例代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HtmlToExcelConverter {
public static void main(String[] args) throws Exception {
// 读取 HTML 文件
String htmlFilePath = "example.html";
Document document = Jsoup.parse(new FileInputStream(htmlFilePath), "UTF-8", "");
// 创建 Excel 工作簿
Workbook workbook = new HSSFWorkbook();
// 创建单元格样式
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setColor(IndexedColors.BLACK.getIndex());
style.setFont(font);
// 创建 Excel 工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 读取 HTML 表格并写入 Excel 工作表
Elements tables = document.getElementsByTag("table");
for (Element table : tables) {
Elements rows = table.getElementsByTag("tr");
for (int i = 0; i < rows.size(); i++) {
Row row = sheet.createRow(i);
Elements cells = rows.get(i).getElementsByTag("td");
for (int j = 0; j < cells.size(); j++) {
String cellText = cells.get(j).text();
row.createCell(j).setCellValue(cellText);
row.getCell(j).setCellStyle(style);
}
}
}
// 写入 Excel 文件
String excelFilePath = "example.xls";
FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Excel 文件已生成!");
}
}
```
您需要将上述代码中的 `example.html` 替换为您要转换的 HTML 文件的路径,将 `example.xls` 替换为您要生成的 Excel 文件的路径。另外,您还可以根据需要调整单元格样式的设置。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)