我打算在ConvertApi提供的Java代码中使用excel到pdf api(REST)。
请共享相同的代码段。
提前致谢。
最佳答案
请尝试下面的代码
图书馆
package com.excel2pdfconvert.example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class Xls2PDFConvertBean {
private File file;
private String outputDir;
private String filesize;
private String filename;
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public void setExcelFile(File file) {
this.file = file;
}
public String getFilesize() {
return filesize;
}
public String getFilename() {
return filename;
}
/**
* Run request for page conversion
* @return resultcode "0" in error, "1" in success
* @throws UnsupportedEncodingException
*/
public String doRequest() throws UnsupportedEncodingException{
String resultcode = "0";
HttpPost httppost = new HttpPost("http://do.convertapi.com/Excel2Pdf");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
entity.addPart("file", new FileBody(file, "binary/octet-stream"));
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+File.separator+filename);
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultcode;
}
}
网页
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="com.excel2pdfconvert.example.Xls2PDFConvertBean" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Excel2Pdf Api Demo
</title>
<script type="text/javascript">
function BeforeConvert() {
document.getElementById('LabelMessage').innerHTML = 'Please wait...';
document.getElementById('HyperLinkFile').innerHTML = '';
document.getElementById('LabelFileSize').innerHTML = '';
document.getElementById('LabelFileName').innerHTML = '';
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div>
<h1>Excel2Pdf Api Demo</h1>
Upload Excel file:
<input type="file" name="excel" />
<input type="submit" name="btnConvert" value="Convert" onclick="BeforeConvert();" id="btnConvert" />
<br />
<br />
<% if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
File uploadedFile = null;
String[] allowedExt = {"csv", "xls", "xlsx", "xlsb", "xlt", "xltx"};
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (! item.isFormField()) {
//Check for valid excel extensions
String fileName = item.getName();
boolean isValid = false;
for(String ext : allowedExt){
if(fileName.contains(ext)){
isValid = true;
break;
}
}
if(isValid){
uploadedFile = new File(application.getRealPath("/") + "/" + fileName);
item.write(uploadedFile);
}
}
}
if(uploadedFile == null){
out.println("<div>Please upload file in following format: csv, xls, xlsx, xlsb, xlt, xltx");
}else{
Xls2PDFConvertBean xls2pdf = new Xls2PDFConvertBean();
xls2pdf.setOutputDir(application.getRealPath("/"));
xls2pdf.setExcelFile(uploadedFile);
String resultcode = xls2pdf.doRequest();
//Remove uploaded file after conversion
uploadedFile.delete();
if(resultcode == null || "False".equals(resultcode)){
out.println("<div>Can not convert file</div>");
}else{
%>
<span id="LabelMessage">Conversion successful </span>
<br />
<a id="HyperLinkFile" href="<%= xls2pdf.getFilename() %>" >Click here to open file </a>
<br />
<span id="LabelFileSize">File size: <%= xls2pdf.getFilesize() %></span>
<br />
<span id="LabelFileName">File name: <%= xls2pdf.getFilename() %></span>
<%
}
}
}else{
%>
<span id="LabelMessage"></span>
<%
}
%>
</div>
</form>
</body>
</html>