excel在我们日常工作生活中会经常用到,通常我们都是用office软件去编写文档。但是对于格式一致的excel文档,如果还是使用人工完成,那绝不是我们软件工程师的姿态了~
下面我就介绍一种方法,不需要复杂的编程,任何编程语言都可使用~
调用别人封装好的API,只要能发送post请求就行,,,特别适合大规模生成相似文档的应用场合
API调用说明:https://www.xiaocongjisuan.com/show/api/44
API传参注意事项:
- appKey:接口唯一标识,在用户后台->应用中心->我的接口查看
- openId:平台id,注册后系统自动生成,在用户后台->用户中心->账户信息查看
- 表格内容是以json类型的字符串表示,只需要按照一定格式拼接字符串(集体规则查看api说明文档),然后调用api即可。
同时接口说明中也有各种开发语言的调用DEMO,如:java、python、php、c#、golang、nodeJS,其实不止上述这些语言,只要可以发出POST请求,就可以使用该接口,非常的方便。这个平台还有很多其它功能的接口,大部分是免费的。像什么天气预报、万年历、老黄历、中文分词、电影数据查询、电子书查询、网盘数据等等,大家慢慢去发现吧!下面贴一下文档内容提取的相关代码:
java版本:
package com.xiaocongjisuan.module.example;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//配置您申请的appKey和openId
public static final String APP_KEY ="yours";
public static final String OPEN_ID ="yours";
//将map型转为请求参数型
public static String urlEncode(Map<String,Object> params) {
if(params==null){return "";};
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,Object> i : params.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
String r=sb.toString();
if(r.endsWith("&")){
r = r.substring(0,r.length()-1);
}
return r;
}
/**
*
* @param requestUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 请求结果
* @throws Exception
*/
public static String requestContent(String requestUrl, Map<String,Object> params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
//组装请求链接
StringBuffer sb = new StringBuffer();
if(method!=null&&method.equalsIgnoreCase("get")){
requestUrl = requestUrl+"?"+urlEncode(params);
}
//默认get
URL url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if(method!=null&&method.equalsIgnoreCase("post")){
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
}
//参数配置
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equalsIgnoreCase("post")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlEncode(params));
} catch (Exception e) {
e.printStackTrace();
}
}
//读取数据
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
public static void main(String[] args) throws Exception{
String domain="http://api.xiaocongjisuan.com/";
String servlet="develop/officeexcelgenerate/get";
String method="get";
String requestUrl=domain+servlet;
Map<String,Object> params=new HashMap<String,Object>();
params.put("appKey",APP_KEY);
params.put("openId",OPEN_ID);
//变动部分
params.put("toFormat","xlsx");
params.put("content","{\"sheets\":[{\"header\":[\"姓名\",\"性别\",\"年龄\"],\"rows\":[[\"张三\",\"男\",\"25\"],[\"李四\",\"男\",\"20\"],[\"小红\",\"女\",\"21\"]]},{\"header\":[\"姓名\",\"成绩\"],\"rows\":[[\"张三\",25],[\"李四\",20],[\"小红\",21]]}]}");
String result=requestContent(requestUrl,params,method);
System.out.println(result);
}
}
python版本:
# -*- coding: utf-8 -*-
# flake8: noqa
__author__ = 'wukong'
import urllib
from urllib import urlencode
#配置您申请的appKey和openId
app_key="***"
open_id="***"
"""
request_url 请求地址
params 请求参数
method 请求方法
"""
def request_content(request_url,params,method):
params = urlencode(params)
if method and method.lower() =="get":
f = urllib.urlopen("%s?%s" % (request_url, params))
else:
f = urllib.urlopen(request_url, params)
content = f.read()
print content
def main():
domain="http://127.0.0.1:8080/xiaocongjisuan/"
servlet="develop/officeexcelgenerate/get"
method="post"
request_url=domain+servlet
#字典
params ={}
params["docName"]=app_key
params["openId"]=open_id
#变动部分
params["toFormat"]="xlsx"
params["content"]="{\"sheets\":[{\"header\":[\"姓名\",\"性别\",\"年龄\"],\"rows\":[[\"张三\",\"男\",\"25\"],[\"李四\",\"男\",\"20\"],[\"小红\",\"女\",\"21\"]]},{\"header\":[\"姓名\",\"成绩\"],\"rows\":[[\"张三\",25],[\"李四\",20],[\"小红\",21]]}]}"
request_content(request_url,params,method)
if __name__ == '__main__':
main()
php版本:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<?php
/**
* @author
* @copyright 2019
*/
header("content-type:text/html;charset=utf-8"); //设置编码
//配置您申请的appKey和openId
$app_key = "***";
$open_id = "***";
/**
$url 请求地址
$params 请求参数
$ispost 请求方法
*/
function http_curl($url,$params=false,$ispost=false){
$httpInfo = array();
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , "xiaocongjisuan");
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
if( $ispost )
{
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
curl_setopt( $ch , CURLOPT_URL , $url );
}
else
{
if($params){
curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
}else{
curl_setopt( $ch , CURLOPT_URL , $url);
}
}
$response = curl_exec( $ch );
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
curl_close( $ch );
return $response;
}
function main(){
global $app_key;
global $open_id;
$domain="http://api.xiaocongjisuan.com/";
$servlet="develop/officeexcelgenerate/get";
$method="get";
$url=$domain."".$servlet;
$params['appKey']=$app_key;
$params['openId']=$open_id;
//变动部分
$params["toFormat"]="xlsx";
$params["content"]="{\"sheets\":[{\"header\":[\"姓名\",\"性别\",\"年龄\"],\"rows\":[[\"张三\",\"男\",\"25\"],[\"李四\",\"男\",\"20\"],[\"小红\",\"女\",\"21\"]]},{\"header\":[\"姓名\",\"成绩\"],\"rows\":[[\"张三\",25],[\"李四\",20],[\"小红\",21]]}]}";
//编码转换
foreach ($params as $key=>$value) {
$params[$key]=mb_convert_encoding($value, "UTF-8", "GBK");
}
$paramstring = http_build_query($params);
$content = http_curl($url,$paramstring,true);
return $content;
}
echo main();
?>
等等.....,其它语言,请看说明文档
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。