方法一:
-
点击链接下载相关jar包
链接:https://pan.baidu.com/s/1Wz0paGJ4CckkfhKVjpfJwQ
提取码:6633 -
将jar包放到项目中,我是直接创建包放到项目里,也可以放到其他地方,自其定义
-
pom进行引用,将jar包路径完整填写
<dependency>
<groupId>aspose-cells.cc</groupId>
<artifactId>aspose-cells</artifactId>
<scope>system</scope>
<version>8.5.2</version>
<systemPath>jar包绝对路径</systemPath>
</dependency>
- 代码实现
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import java.io.File;
import java.io.FileOutputStream;
public class StyleStudy {
public static void main(String[] args) {
try {
// 读取要转化的Excel文件
Workbook wb = new Workbook("C:\\Users\\Administrator\\Desktop\\1697506563270.xlsx");
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
// 创建PDF输出流
String pdfFileName = "C:\\Users\\Administrator\\Desktop"+System.currentTimeMillis()+".pdf";
FileOutputStream fileOutputStream = new FileOutputStream(new File(pdfFileName));
wb.save(fileOutputStream, pdfSaveOptions);
System.out.println("PDF转换成功=========");
}catch (Exception e){
e.printStackTrace();
}
}
}
方法二(推荐,效率低些):
上代码
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
public class StockSellTest {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
XSSFWorkbook workbook = null;
try {
//Excel文件数据
String pdfFileName = "C:\\Users\\Administrator\\Desktop\\01.pdf";
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\01.xlsx");
ZipSecureFile.setMinInflateRatio(-1.0d);// 压缩文件不符合安全限制会抛出异常
workbook = new XSSFWorkbook(fileInputStream);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(pdfFileName));
document.open();
Sheet sheet = workbook.getSheetAt(0); // Assuming data is on the first sheet
for (Row row : sheet) {
for (Cell cell : row) {
cell.setCellType(CellType.STRING);// 非字符串类型会转化失败,因此要先将该单元格的类型设置为String
String cellValue = cell.getStringCellValue(); // You can customize this based on cell type
document.add(new Paragraph(cellValue));
}
}
document.close();
workbook.close();
fileInputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}