C# 调用百度API批量识别发票,并存到EXCEL
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/f406f2185184456daa9ba7829c26138d.png#pic_center)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using RestSharp;//依赖版本106.15.0 https://www.nuget.org/packages/RestSharp/106.15.0
using Newtonsoft.Json;
using IniParser;
using IniParser.Model; //https://www.nuget.org/packages/Newtonsoft.Json
namespace 发票识别
{
public class rest
{
public string str1;
public string str2;
private void sstname()
{
var parser = new FileIniDataParser();
string iniFilePath = "config.ini";
try
{
IniData data = parser.ReadFile(iniFilePath);
string sectionName = "Apidate"; // 替换为你的节名
string keyName = "AKEY"; // 替换为你的键名
string keysName = "SKEY"; // 替换为你的键名
// 获取特定节和键的值
string value = data[sectionName][keyName];
string value1 = data[sectionName][keysName];
str1 = value;
str2 = value1;
}
catch (Exception ex)
{
//Console.WriteLine("Error reading INI file: " + ex.Message);
}
}
//string API_KEY = str1.ToString();
//string SECRET_KEY = str2;
public static string StrPanth(string pathname)
{
var client = new RestClient($"https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token={GetAccessToken()}");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
// pdf_file 可以通过 GetFileBase64Content('C:\fakepath\2491816599 00003.PDF') 方法获取
var str = GetFileContentAsBase64(pathname);
request.AddParameter("pdf_file", str);
request.AddParameter("seal_tag", "false");
IRestResponse response = client.Execute(request);
Thread.Sleep(200);
return response.Content;
//return result;
}
static string GetAccessToken()
{
var parser = new FileIniDataParser();
string iniFilePath = "config.ini";
IniData data = parser.ReadFile(iniFilePath);
string sectionName = "Apidate"; // 替换为你的节名
string keyName = "AKEY"; // 替换为你的键名
string keysName = "SKEY"; // 替换为你的键名
// 获取特定节和键的值
string value = data[sectionName][keyName];
string value1 = data[sectionName][keysName];
var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", value);
request.AddParameter("client_secret", value1);
IRestResponse response = client.Execute(request);
//Console.WriteLine(response.Content);
var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
return result.access_token.ToString();
}
static string GetFileContentAsBase64(string path)
{
using (FileStream filestream = new FileStream(path, FileMode.Open))
{
byte[] arr = new byte[filestream.Length];
filestream.Read(arr, 0, (int)filestream.Length);
string base64 = Convert.ToBase64String(arr);
return base64;
}
}
}
}