Excel to HTML Table Converter in Java
| Column 1 | Column 2 | Column 3 | Column 4 | Column 5 |
| Row 1, Cell 1 | Row 1, Cell 2 | Row 1, Cell 3 | Row 1, Cell 4 | Row 1, Cell 5 |
| Row 2, Cell 1 | Row 2, Cell 2 | Row 2, Cell 3 | Row 2, Cell 4 | Row 2, Cell 5 |
| Row 3, Cell 1 | Row 3, Cell 2 | Row 3, Cell 3 | Row 3, Cell 4 | Row 3, Cell 5 |
import java.awt.*;
import java.io.*;
import java.util.Iterator;
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;
public class test12 {
public static void main(String[] args) throws Exception {
String excelFilePath = "input.xlsx";
File inputFile = new File(excelFilePath);
//Get the workbook instance for XLSX file
Workbook workbook = null;
if (excelFilePath.endsWith("xlsx")) {
workbook = new XSSFWorkbook(new FileInputStream(inputFile));
} else if (excelFilePath.endsWith("xls")) {
workbook = new HSSFWorkbook(new FileInputStream(inputFile));
}
//Get the first sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Create a new HTML table
StringBuffer htmlTable = new StringBuffer("<table style=\"border-collapse: collapse; width: 100%;\">");
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//Create a new HTML table row
htmlTable.append("<tr>");
//Iterate through each columns from the row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Create a new HTML table cell
htmlTable.append("<td style=\"border: 1px solid #ddd; padding: 8px;\">");
//Get the cell value and append to HTML table cell
switch (cell.getCellType()) {
case STRING:
htmlTable.append(cell.getStringCellValue());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
htmlTable.append(cell.getDateCellValue().getTime());
} 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);
}
//Close the HTML table cell
htmlTable.append("</td>");
}
//Close the HTML table row
htmlTable.append("</tr>");
}
//Close the HTML table
htmlTable.append("</table>");
//Close the workbook
workbook.close();
//Create a new HTML file and write the table content
String htmlFilePath = "output.html";
File htmlFile = new File(htmlFilePath);
BufferedWriter writer = new BufferedWriter(new FileWriter(htmlFile));
writer.write(htmlTable.toString());
writer.close();
//Open the HTML file in default browser
Desktop.getDesktop().browse(htmlFile.toURI());
}
}
原文地址: https://www.cveoy.top/t/topic/f0Xg 著作权归作者所有。请勿转载和采集!