How do java, ruby, python, php, etc. generate excel documents?

Keywords: Java PHP Excel Programming

excel is often used in our daily work and life. Usually we use office software to write documents. But for excel documents with the same format, if it is still done manually, it is by no means the attitude of our software engineers.~

Now I'll introduce a method that does not require complex programming and can be used in any programming language.~
Call other people's encapsulated API, as long as it can send post requests, especially suitable for large-scale generation of similar documents applications.

API Call Description: https://www.xiaocongjisuan.com/show/api/44
API Reference Notes:

  1. appKey: Unique ID of the interface, in the user background - > Application Center - > My interface view
  2. openId: Platform id, automatically generated after registration, in the user background - > User Center - > account information view
  3. The contents of the table are represented by json type strings. They only need to splice strings in a certain format (group rules to view api specification documents), and then call api.

At the same time, there are also various development languages called DEMO in the interface description, such as java, python, php, c#, golang, node JS. In fact, these languages are not only mentioned above, as long as POST requests can be made, the interface can be used, which is very convenient. The platform also has many interfaces for other functions, most of which are free. Like what weather forecast, calendar, old Huang calendar, Chinese word segmentation, movie data query, e-book query, web data and so on, you slowly find it! Next, paste the relevant code of document content extraction:

java version:

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";
     
     //Configure the appKey and openId you applied for
     public static final String APP_KEY ="yours";
     public static final String OPEN_ID ="yours";
     
     //Change map type to request parameter type
     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 Request address
     * @param params Request parameters
     * @param method Request method
     * @return Request result
     * @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 {

            //Assembly request link
            StringBuffer sb = new StringBuffer();
            
            if(method!=null&&method.equalsIgnoreCase("get")){
                requestUrl = requestUrl+"?"+urlEncode(params);
            }

            //Default 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);
            }

            //Parameter configuration
            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();
                }
            }
            
            //Read data
            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);

        //Variable part
        params.put("toFormat","xlsx");
        params.put("content","{\"sheets\":[{\"header\":[\"Full name\",\"Gender\",\"Age\"],\"rows\":[[\"Zhang San\",\"male\",\"25\"],[\"Li Si\",\"male\",\"20\"],[\"Xiaohong\",\"female\",\"21\"]]},{\"header\":[\"Full name\",\"achievement\"],\"rows\":[[\"Zhang San\",25],[\"Li Si\",20],[\"Xiaohong\",21]]}]}");
        
        String result=requestContent(requestUrl,params,method);
        System.out.println(result);
    }
}

python version:

# -*- coding: utf-8 -*-
# flake8: noqa
__author__ = 'wukong'

import urllib
from urllib import urlencode

#Configure the appKey and openId you applied for
app_key="***"
open_id="***"

"""
request_url Request address
params Request parameters
method Request 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
    
    #Dictionaries
    params ={}
    
    params["docName"]=app_key
    params["openId"]=open_id
    
    #Variable part
    params["toFormat"]="xlsx"
    params["content"]="{\"sheets\":[{\"header\":[\"Full name\",\"Gender\",\"Age\"],\"rows\":[[\"Zhang San\",\"male\",\"25\"],[\"Li Si\",\"male\",\"20\"],[\"Xiaohong\",\"female\",\"21\"]]},{\"header\":[\"Full name\",\"achievement\"],\"rows\":[[\"Zhang San\",25],[\"Li Si\",20],[\"Xiaohong\",21]]}]}"


    request_content(request_url,params,method)
    
if __name__ == '__main__':
    main()

php version:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<?php

/**
 * @author 
 * @copyright 2019
 */
 
header("content-type:text/html;charset=utf-8");         //Set encoding
 
//Configure the appKey and openId you applied for
$app_key = "***";
$open_id = "***";

/**
$url Request address
$params Request parameters
$ispost Request method
*/

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;
    
    //Variable part
    $params["toFormat"]="xlsx";
    $params["content"]="{\"sheets\":[{\"header\":[\"Full name\",\"Gender\",\"Age\"],\"rows\":[[\"Zhang San\",\"male\",\"25\"],[\"Li Si\",\"male\",\"20\"],[\"Xiaohong\",\"female\",\"21\"]]},{\"header\":[\"Full name\",\"achievement\"],\"rows\":[[\"Zhang San\",25],[\"Li Si\",20],[\"Xiaohong\",21]]}]}";

    //Code conversion
    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();
?>

Wait a minute.... For other languages, see the documentation.

Posted by affluent980 on Thu, 10 Oct 2019 05:24:12 -0700