下載依賴的jar包,將包添加到工程目錄下的resources/lib/中
鏈接: https://pan.baidu.com/s/15kwoT2eeTGVjNcvZRdccpw?pwd=rcg1
提取碼: rcg1
在pom.xml添加依賴
<!--添加本地的jacob.jar包-->
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/jacob.jar</systemPath>
</dependency>
轉(zhuǎn)pdf
/**
* 根據(jù)格式類型轉(zhuǎn)換xls文件
*
* @param srcPath xls path 源文件
* @param descPath pdf path 目標(biāo)文件
* @return the file
* @throws Exception the exception
*/
public File convertXlsPDF(String srcPath, String descPath) throws Exception {
// 實(shí)例化ComThread線程與ActiveXComponent
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
// 隱藏時(shí)進(jìn)行應(yīng)用操作
app.setProperty("Visible", new Variant(false));
app.setProperty("DisplayAlerts", new Variant(false));
// 實(shí)例化模板Document對象
Dispatch excels = app.getProperty("Workbooks").toDispatch();
// 打開Document進(jìn)行另存為操作
Dispatch excel = Dispatch.call(excels, "Open", srcPath, false, true).toDispatch();
Dispatch.call(excel, "ExportAsFixedFormat", XLTYPE_PDF, descPath);
Dispatch.call(excel, "Close", false);
return new File(descPath);
} catch (Exception e) {
throw e;
} finally {
// 釋放線程與ActiveXComponent
app.invoke("Quit", new Variant[]{});
ComThread.Release();
}
}
轉(zhuǎn)xlsx
/**
* 根據(jù)格式類型轉(zhuǎn)換xls文件
*
* @param srcPath xls path 源文件
* @param descPath xlsx path 目標(biāo)文件
* @return the file
* @throws Exception the exception
*/
public File convertXlsfmt(String srcPath, String descPath) throws Exception {
// 實(shí)例化ComThread線程與ActiveXComponent
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
// 隱藏時(shí)進(jìn)行應(yīng)用操作
app.setProperty("Visible", new Variant(false));
app.setProperty("DisplayAlerts", new Variant(false));
// 實(shí)例化模板Document對象
Dispatch excels = app.getProperty("Workbooks").toDispatch();
// 打開Document進(jìn)行另存為操作
Dispatch excel = Dispatch.call(excels, "Open", srcPath, false, true).toDispatch();
Dispatch.invoke(excel,
"SaveAs",
Dispatch.Method,
new Object[]{descPath, new Variant(EXCEL_XML_2_XLS)
},
new int[1]);
Variant f = new Variant(false);
Dispatch.call(excel, "Close", f);
return new File(descPath);
} catch (Exception e) {
throw e;
} finally {
// 釋放線程與ActiveXComponent
app.invoke("Quit", new Variant[]{});
ComThread.Release();
}
}