使用 java 将 excel 文件转 html、pdf ,以及 pdf 合并和拆分
在Java中,可以使用Apache POI库来读取和写入Excel文件,以及使用iText库来创建PDF文件。以下是将Excel转换为HTML和PDF,以及合并和拆分PDF文件的示例代码。
转换Excel到HTML:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class ExcelToHtml {
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook(new FileInputStream("example.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<html><body>");
for (Row row : sheet) {
htmlBuilder.append("<tr>");
for (Cell cell : row) {
htmlBuilder.append("<td>");
htmlBuilder.append(cell.toString());
htmlBuilder.append("</td>");
}
htmlBuilder.append("</tr>");
}
htmlBuilder.append("</body></html>");
try (FileWriter writer = new FileWriter("example.html")) {
writer.write(htmlBuilder.toString());
}
}
}
转换Excel到PDF:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class ExcelToPdf {
public static void main(String[] args) throws IOException, DocumentException {
Workbook workbook = new XSSFWorkbook(new FileInputStream("example.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("example.pdf"));
document.open();
for (Row row : sheet) {
Paragraph paragraph = new Paragraph();
for (Cell cell : row) {
paragraph.add(new Paragraph(cell.toString()));
}
document.add(paragraph);
}
document.close();
}
}
合并PDF文件:
import com.itextpdf.kernel.pdf.*;
import java.io.*;
public class MergePdf {
public static void main(String[] args) throws IOException {
PdfReader pdfReader1 = new PdfReader("file1.pdf");
PdfReader pdfReader2 = new PdfReader("file2.pdf");
PdfWriter pdfWriter = new PdfWriter("merged.pdf");
PdfDocu
评论已关闭