当前位置:   article > 正文

C#使用EPPlus获取excel单元格内容调用百度翻译API将结果存入SQLite数据库_百度翻译可以自己更新数据库吗

百度翻译可以自己更新数据库吗

需求分析

有这样一个需求,将Excel文件中指定的行和列的内容,翻译成中文,并将翻译的结果存入SQLite数据库的内部代码表中。

操作的步骤是:

  1. 打开Excel找到需要翻译的单元格内容,并将其复制
  2. 打开浏览器访问百度翻译,粘贴进行翻译
  3. 将翻译的内容粘贴到添加内部代码界面进行添加

手工操作的话,一个Excel中需要复制粘贴 237 * 6 = 1422 次,有4个Excel,大约需要复制粘贴 1422 * 4 = 5688 次。如此重复劳动的工作量可想而知。

原型设计

为了解决上述问题,拜托手工操作的繁重任务,需要开发一个小软件,需具备如下功能:

  1. 可以选择需要操作的Excel文件
  2. 设置需要进行入库与翻译的单元格范围,如:2-237行,B-G列
  3. 使用百度翻译API进行翻译
  4. 显示翻译内容与进度
  5. 将翻译结果保存到SQLite数据库

如下图所示:
在这里插入图片描述
在这里插入图片描述

nuget安装依赖包

用到的nuget包共有3个,其他的都为依赖项如下:

  1. EPPlus
  2. Newtonsoft.Json
  3. System.Data.SQLite

在这里插入图片描述

关键代码实现

关键代码包含如下:

EPPlus获取单元格内容

EPPlus官方文档:https://epplussoftware.com/zh/Developers

// 引用命名空间
using BaiduTransDemo.DataAccess;
using Newtonsoft.Json;
using OfficeOpenXml;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

 // EEPlus处理excel文件
 var excelFile = new FileInfo(txt_excelPath.Text);
 ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
 Task.Run(() =>
 {
     using (var package = new ExcelPackage(excelFile))
     {
         string dtcColStr = "ABCDEFGHIJKMLNOPQRST"; // excel列,用于列循环

         #region 遍历故障码英文描述,进行百度翻译,得到故障码中文描述
         // 循环行
         for (int i = dtcRowStart; i <= dtcRowEnd; i++)
         {
             DataGridViewRow row = new DataGridViewRow();
             DataGridViewTextBoxCell cellCode = new DataGridViewTextBoxCell();
             DataGridViewTextBoxCell cellDst = new DataGridViewTextBoxCell();
             DataGridViewTextBoxCell cellSrc = new DataGridViewTextBoxCell();
             DataGridViewTextBoxCell cellWorkActionZh = new DataGridViewTextBoxCell();
             DataGridViewTextBoxCell cellWorkActionEn = new DataGridViewTextBoxCell();
             // 循环故障代码描述列
             if (chk_dtcColType.Checked)
             {
                 string[] dtcColTypeArr = txt_dtcColType.Text.Split(',');
                 for (int j = 0; j <= dtcColTypeArr.Length; j++)
                 {
                     string cellKey = string.Concat(dtcColTypeArr[j], i); // 得到需要操作的单元格定位 例如:A2,列A,行2
                     string cellKeyToTrans = package.Workbook.Worksheets["sm_candela_file_adv"].Cells[cellKey].Text; // 获取指定单元格内容
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

访问SQLite数据库

SQLite数据库访问帮助类,代码如下:

#region << 版 本 注 释 >>

/*----------------------------------------------------------------
 * 版权所有 (c) 2021  保留所有权利。
 * CLR版本:4.0.30319.42000
 * 机器名称:DESKTOP-T90SFH8
 * 公司名称:
 * 命名空间:BaiduTransDemo
 * 唯一标识:914572c8-d2db-4889-971e-d5cb11a8b53c
 * 文件名:SQLiteHelper
 * 当前用户域:DESKTOP-T90SFH8
 *
 * 创建者:Cgs
 * 电子邮箱:1003590782@qq.com
 * 创建时间:9/15/2021 11:29:36 AM
 * 版本:V1.0.0
 * 描述:SQLiteHelper帮助类
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 时间:
 * 修改说明:
 *
 * 版本:V1.0.1
 *----------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using System;
using System.Collections;
using System.Data;
using System.Data.SQLite;

namespace BaiduTransDemo
{
    /// <summary>
    /// SQLiteHelper 的摘要说明
    /// </summary>
    public class SQLiteHelper
    {
        /// <summary>
        /// 数据库联接串
        /// </summary>
        public static string ConnectionString = System.Windows.Forms.Application.StartupPath + "\\newgajck_adas.db";

        public SQLiteHelper(string conn)
        {
            ConnectionString = conn;
        }

        public SQLiteHelper(string filePath, string password)
        {
            ConnectionString = new SQLiteConnectionStringBuilder() { DataSource = filePath, Password = password }.ConnectionString;
        }

        private static SQLiteConnection GetConn()
        {
            //构建连接字符串
            SQLiteConnection conn = new SQLiteConnection(ConnectionString);
            return conn;
        }

        #region 公用方法

        public int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        public bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool Exists(string strSql, params SQLiteParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion 公用方法

        #region 执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>
        public void ExecuteSqlTran(ArrayList SQLStringList)
        {
            using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                conn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = conn;
                SQLiteTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString, string content)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public object GetSingle(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException e)
                    {
                        connection.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SQLiteDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public SQLiteDataReader ExecuteReader(string strSQL)
        {
            SQLiteConnection connection = new SQLiteConnection(ConnectionString);
            SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
            try
            {
                connection.Open();
                SQLiteDataReader myReader = cmd.ExecuteReader();
                return myReader;
            }
            catch (System.Data.SQLite.SQLiteException e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataTable QueryTable(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }

                return ds.Tables[0];
            }

            //return new DataTable();
        }

        #endregion 执行简单SQL语句

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        #endregion 执行带参数的SQL语句

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param>
        public void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                conn.Open();
                using (SQLiteTransaction trans = conn.BeginTransaction())
                {
                    SQLiteCommand cmd = new SQLiteCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();

                            trans.Commit();
                        }
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public object GetSingle(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SQLiteDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms)
        {
            SQLiteConnection connection = new SQLiteConnection(ConnectionString);
            SQLiteCommand cmd = new SQLiteCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SQLiteDataReader myReader = cmd.ExecuteReader();
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SQLite.SQLiteException e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        /// <summary>
        /// </summary>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <param name="Sqlstr"></param>
        /// <returns></returns>
        public static DataSet ExecuteDs(int pagesize, int pageindex, String sqlstr)
        {
            using (SQLiteConnection conn = GetConn())
            {
                DataSet ds = new DataSet();
                SQLiteCommand cmd = new SQLiteCommand(sqlstr, conn);//执行语句
                SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
                int startPost = pagesize;
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                da.SelectCommand = cmd;
                try
                {
                    conn.Open();
                    da.Fill(ds, pagesize * (pageindex - 1), pagesize, "PagerTable");
                    return ds;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    da.Dispose();
                    conn.Close();
                }
            }
        }

        private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SQLiteParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        /// <summary>
        /// 过滤SQL语句,防止注入
        /// </summary>
        /// <returns> </returns>
        public static string FilterSql(string sSql)
        {
            //int srcLen, decLen = 0;
            //srcLen = sSql.Length;
            sSql = sSql.ToLower().Trim();
            sSql = sSql.Replace("exec ", "");
            sSql = sSql.Replace("=", "");
            sSql = sSql.Replace("and ", "");
            sSql = sSql.Replace("or ", "");
            sSql = sSql.Replace("insert ", "");
            sSql = sSql.Replace("delete ", "");
            sSql = sSql.Replace("master ", "");
            sSql = sSql.Replace("truncate ", "");
            sSql = sSql.Replace("declare ", "");
            sSql = sSql.Replace("create ", "");
            sSql = sSql.Replace("xp_", "no");
            return sSql;
            //decLen = sSql.Length;
            //if (srcLen == decLen) return false; else return true;
        }

        /// <summary>
        /// C# null转成sql null
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object CSharpNullConvertDbNull(object obj)
        {
            return obj ?? DBNull.Value;
        }

        #region SqlDataReader GetReaderByStoredProcedure 返回DataReader的查询方法存储过程

        /// <summary>
        /// 返回DataReader的查询方法(存储过程)
        /// 使用完SqlDataReader一定要关闭,否则会造成连接池溢出
        /// </summary>
        /// <param name="safeSql"></param>
        /// <returns></returns>
        public static SQLiteDataReader GetReaderByStoredProcedure(string name)
        {
            SQLiteConnection conn = GetConn();
            try
            {
                conn.Open();
                SQLiteCommand com = new SQLiteCommand();
                com.Connection = conn;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = name;
                SQLiteDataReader reader = com.ExecuteReader(CommandBehavior.CloseConnection);
                return reader;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 返回DataReader的查询方法(带参数)(存储过程)
        /// 使用完SqlDataReader一定要关闭,否则会造成连接池溢出
        /// </summary>
        /// <param name="safeSql"></param>
        /// <returns></returns>
        public static SQLiteDataReader GetReaderByStoredProcedure(string name, params SQLiteParameter[] paras)
        {
            SQLiteConnection conn = GetConn();

            try
            {
                conn.Open();
                SQLiteCommand com = new SQLiteCommand();
                com.Connection = conn;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = name;
                com.Parameters.AddRange(paras);
                SQLiteDataReader reader = com.ExecuteReader(CommandBehavior.CloseConnection);
                return reader;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion SqlDataReader GetReaderByStoredProcedure 返回DataReader的查询方法存储过程

        /// <summary>
        /// DataAdapter读取数据,返回DataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql)
        {
            SQLiteConnection conn = GetConn();
            //创建一个DataSet集
            DataSet ds = new DataSet();
            try
            {
                //创建一个DataAdapter对象
                SQLiteDataAdapter sda = new SQLiteDataAdapter(sql, conn);
                conn.Open();
                //将结果填充到table中
                sda.Fill(ds);
                //返回table
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476
  • 477
  • 478
  • 479
  • 480
  • 481
  • 482
  • 483
  • 484
  • 485
  • 486
  • 487
  • 488
  • 489
  • 490
  • 491
  • 492
  • 493
  • 494
  • 495
  • 496
  • 497
  • 498
  • 499
  • 500
  • 501
  • 502
  • 503
  • 504
  • 505
  • 506
  • 507
  • 508
  • 509
  • 510
  • 511
  • 512
  • 513
  • 514
  • 515
  • 516
  • 517
  • 518
  • 519
  • 520
  • 521
  • 522
  • 523
  • 524
  • 525
  • 526
  • 527
  • 528
  • 529
  • 530
  • 531
  • 532
  • 533
  • 534
  • 535
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • 551
  • 552
  • 553
  • 554
  • 555
  • 556
  • 557
  • 558
  • 559
  • 560
  • 561
  • 562
  • 563
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • 574
  • 575
  • 576
  • 577
  • 578
  • 579
  • 580
  • 581
  • 582
  • 583
  • 584
  • 585
  • 586
  • 587
  • 588
  • 589
  • 590
  • 591
  • 592
  • 593
  • 594
  • 595
  • 596
  • 597
  • 598
  • 599
  • 600
  • 601
  • 602
  • 603
  • 604
  • 605
  • 606
  • 607
  • 608
  • 609
  • 610
  • 611
  • 612
  • 613
  • 614
  • 615
  • 616
  • 617
  • 618
  • 619
  • 620
  • 621
  • 622
  • 623
  • 624
  • 625
  • 626
  • 627
  • 628
  • 629
  • 630
  • 631
  • 632
  • 633
  • 634
  • 635
  • 636
  • 637
  • 638
  • 639
  • 640
  • 641
  • 642
  • 643
  • 644
  • 645
  • 646
  • 647
  • 648
  • 649
  • 650
  • 651
  • 652
  • 653
  • 654
  • 655
  • 656
  • 657
  • 658
  • 659
  • 660
  • 661
  • 662
  • 663
  • 664
  • 665
  • 666
  • 667
  • 668
  • 669
  • 670
  • 671
  • 672
  • 673
  • 674
  • 675
  • 676
  • 677
  • 678
  • 679

WinForm跨线程访问控件

处理复杂任务时可能会导致主界面UI线程阻塞,出现UI界面假死的情况,为了防止这种问题出现,需要跨线程操作WinForm控件,如下:

#region << 版 本 注 释 >>

/*----------------------------------------------------------------
 * 版权所有 (c) 2021  保留所有权利。
 * CLR版本:4.0.30319.42000
 * 机器名称:DESKTOP-T90SFH8
 * 公司名称:
 * 命名空间:BaiduTransDemo
 * 唯一标识:f43c8925-8971-4949-9f33-142d85ff440e
 * 文件名:ThreadCrossHelper
 * 当前用户域:DESKTOP-T90SFH8
 *
 * 创建者:Cgs
 * 电子邮箱:1003590782@qq.com
 * 创建时间:9/15/2021 4:59:05 PM
 * 版本:V1.0.0
 * 描述:跨线程操作WinForm控件帮助类
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 时间:
 * 修改说明:
 *
 * 版本:V1.0.1
 *----------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using System;
using System.Windows.Forms;

namespace BaiduTransDemo
{
    /// <summary>
    /// ThreadCrossHelper 的摘要说明
    /// </summary>
    public class ThreadCrossHelper
    {
        #region <属性>

        public delegate void RichTextBoxDelegate(RichTextBox ric, string msg);
        public delegate void DataGridViewDelegate(DataGridView dgv, DataGridViewRow row);

        #endregion <属性>

        #region <方法>

        public static void ShowMsg(RichTextBox ric, string msg)
        {
            if (!string.IsNullOrEmpty(msg))
            {
                if (ric.InvokeRequired)//获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中。
                {
                    RichTextBoxDelegate d = new RichTextBoxDelegate(ShowMsg);
                    ric.BeginInvoke(d, ric, msg);//在创建控件的基础句柄所在线程上,用指定的参数异步执行指定委托。
                }
                else
                {
                    ric.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + msg + Environment.NewLine);
                    ric.ScrollToCaret();
                }
            }
        }

        public static void ShowInfo(RichTextBox ric, string msg)
        {
            if (!string.IsNullOrEmpty(msg))
            {
                if (ric.InvokeRequired)
                {
                    RichTextBoxDelegate d = new RichTextBoxDelegate(ShowInfo);
                    ric.BeginInvoke(d, ric, msg);
                }
                else
                {
                    ric.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 报告单编号为【" + msg + "】的记录上传成功!" + Environment.NewLine);
                    ric.ScrollToCaret();
                }
            }
        }

        public static void ShowInfo(RichTextBox ric, string msg, string ex)
        {
            if (!string.IsNullOrEmpty(msg))
            {
                if (ric.InvokeRequired)
                {
                    RichTextBoxDelegate d = new RichTextBoxDelegate(ShowInfo);
                    ric.BeginInvoke(d, ric, msg);
                }
                else
                {
                    ric.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 报告单编号为【" + msg + "】的记录上传失败!" + ex + Environment.NewLine);
                    ric.ScrollToCaret();
                }
            }
        }

        /// <summary>
        /// 跨线程给DataGridView添加DataGridViewRow
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="row">DataGridViewRow</param>
        public static void AddRowToDgv(DataGridView dgv, DataGridViewRow row)
        {
            if (row != null)
            {
                if (dgv.InvokeRequired)
                {
                    DataGridViewDelegate d = new DataGridViewDelegate(AddRowToDgv);
                    dgv.BeginInvoke(d, dgv, row);
                }
                else
                {
                    dgv.Rows.Add(row);
                    dgv.FirstDisplayedScrollingRowIndex = dgv.Rows.Count - 1;
                }
            }
        }

        /// <summary>
        /// 跨线程给DataGridView添加DataGridViewRow
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="index">DataGridViewRow</param>
        public static void DgvSetScrollingRowIndex(DataGridView dgv,int index)
        {
            MethodInvoker mi = new MethodInvoker(() =>
            {
                dgv.FirstDisplayedScrollingRowIndex = index;
            });
            dgv.BeginInvoke(mi);
        }

        /// <summary>
        /// 跨线程调用进度条前进
        /// </summary>
        /// <param name="progressBar"></param>
        public static void PerformStep(ProgressBar progressBar)
        {
            MethodInvoker mi = new MethodInvoker(() =>
            {
                progressBar.PerformStep();
            });
            progressBar.BeginInvoke(mi);
        }

        #endregion <方法>
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150

调用百度翻译API

百度翻译开放平台官方文档:https://api.fanyi.baidu.com/doc/21

调用百度翻译API帮助类,如下:

#region << 版 本 注 释 >>

/*----------------------------------------------------------------
 * 版权所有 (c) 2021  保留所有权利。
 * CLR版本:4.0.30319.42000
 * 机器名称:DESKTOP-T90SFH8
 * 公司名称:
 * 命名空间:BaiduTransDemo
 * 唯一标识:f5edde70-c3fa-4977-91b9-f74ea73df514
 * 文件名:BaiduTransApiHelper
 * 当前用户域:DESKTOP-T90SFH8
 *
 * 创建者:Cgs
 * 电子邮箱:1003590782@qq.com
 * 创建时间:9/15/2021 1:04:05 PM
 * 版本:V1.0.0
 * 描述:百度翻译API帮助类
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 时间:
 * 修改说明:
 *
 * 版本:V1.0.1
 *----------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Web;


namespace BaiduTransDemo
{
    /// <summary>
    /// BaiduTransApiHelper 的摘要说明
    /// </summary>
    public class BaiduTransApiHelper
    {
        #region <方法>

        // 计算MD5值
        public static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串,
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }

        /// <summary>
        /// 调用百度翻译API
        /// </summary>
        /// <param name="q">原文</param>
        /// <param name="from">源语言</param>
        /// <param name="to">目标语言</param>
        /// <returns></returns>
        public static string Trans(string q, string from = "en", string to = "zh")
        {
            // 改成您的APP ID
            string appId = "XXXXXXXXXXXXXX";
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            // 改成您的密钥
            string secretKey = "XXXXXXXXXXXXXX";
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

        #endregion <方法>
    }

    /// <summary>
    /// 百度翻译JSON根
    /// </summary>
    public class Rootobject
    {
        public string from { get; set; }
        public string to { get; set; }
        public Trans_Result[] trans_result { get; set; }
    }

    /// <summary>
    /// 百度翻译JSON结果
    /// </summary>
    public class Trans_Result
    {
        public string src { get; set; }
        public string dst { get; set; }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/738933
推荐阅读
相关标签
  

闽ICP备14008679号