Java将Excel表格完美呈现在网页上
Java将Excel表格完美呈现在网页上
你是否需要将Excel表格数据清晰地展示在网页上?本文将教你如何使用Java和Apache POI库,将Excel表格转换为HTML表格,并完美呈现在网页上。
1. 准备工作
-
添加Apache POI依赖: 在你的项目中添加Apache POI库的依赖。如果你使用Maven,可以将以下依赖添加到你的pom.xml文件中:xml
org.apache.poi poi 5.2.2 org.apache.poi poi-ooxml 5.2.2 -
创建Servlet: 创建一个新的Java Servlet,用于处理Excel文件并生成HTML表格。
2. 代码实现
以下是一个简单的Servlet代码示例,它可以读取Excel文件并将数据转换为HTML表格:javaimport java.io.;import javax.servlet.;import javax.servlet.http.;import org.apache.poi.ss.usermodel.;import org.apache.poi.xssf.usermodel.;import org.apache.poi.hssf.usermodel.;import org.apache.poi.ss.util.;import org.apache.poi.hssf.util.;import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;
public class ExcelToWeb extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置响应内容类型为HTML response.setContentType('text/html;charset=UTF-8');
// 获取Excel文件路径 String excelFilePath = '巴新EDEVU水库数据处理表.xls'; // 你可以根据实际情况修改文件路径,例如从用户上传中获取
try { // 读取Excel文件 File inputFile = new File(excelFilePath); Workbook workbook = null; if (excelFilePath.endsWith('xlsx')) { workbook = new XSSFWorkbook(new FileInputStream(inputFile)); } else if (excelFilePath.endsWith('xls')) { workbook = new HSSFWorkbook(new FileInputStream(inputFile)); }
// 获取第一个工作表 Sheet sheet = workbook.getSheetAt(0);
// 创建HTML表格 StringBuffer htmlTable = new StringBuffer('<table style='border-collapse: collapse; width: 100%;'>');
// 遍历每一行 Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); htmlTable.append('<tr>');
// 遍历每一列 Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); htmlTable.append('<td style='border: 1px solid #ddd; padding: 8px;'>');
// 获取单元格值并添加到HTML表格单元格 switch (cell.getCellType()) { case STRING: htmlTable.append(cell.getStringCellValue()); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss'); String formattedDate = sdf.format(date); htmlTable.append(formattedDate); } else { htmlTable.append(cell.getNumericCellValue()); } break; case BOOLEAN: htmlTable.append(cell.getBooleanCellValue()); break; case FORMULA: htmlTable.append(cell.getCellFormula()); break; case BLANK: htmlTable.append(''); break; default: htmlTable.append(cell); }
htmlTable.append('</td>'); } htmlTable.append('</tr>'); } htmlTable.append('</table>');
// 关闭工作簿 workbook.close();
// 将HTML表格内容写入响应输出流 PrintWriter out = response.getWriter(); out.println(htmlTable.toString());
} catch (Exception e) { e.printStackTrace(); response.getWriter().println('读取Excel文件时发生错误:' + e.getMessage()); }
原文地址: https://www.cveoy.top/t/topic/f0Xt 著作权归作者所有。请勿转载和采集!