常用的Common助手类文件

工作中遇到的常用助手类,这里只有自己用到的一些东西。

EmaileHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using OpenPop.Pop3;
using OpenPop.Mime;
using System.IO;
using System.Collections;


namespace Common
{

    public static class EmailHelper
    {
        #region 
        private static Dictionary<string, Message> EmaiMessagelList = new Dictionary<string, Message>();
        public static int EmailCount = 0;
        public static bool isDownLoad = false;
        #endregion

        #region  ServerInfo
        private static string SendServer = System.Configuration.ConfigurationManager.AppSettings["ESendserver"].ToString();
        private static string From = System.Configuration.ConfigurationManager.AppSettings["ESendAdd"].ToString();
        private static string Pwd = System.Configuration.ConfigurationManager.AppSettings["ESendpwd"].ToString();

        private static string ReceiveServer = System.Configuration.ConfigurationManager.AppSettings["EReceiveserver"].ToString();
        private static string ReceiveAdd = System.Configuration.ConfigurationManager.AppSettings["EReceiveAdd"].ToString();
        private static string ReceivePwd = System.Configuration.ConfigurationManager.AppSettings["EReceivepwd"].ToString();
        #endregion

        #region  SendEmail

        /// <summary>
        /// 发送邮件(统一的发件人)
        /// </summary>
        /// <param name="toemailadd">收件人地址</param>
        /// <param name="cclist">抄送人地址</param>
        /// <param name="subject">主题</param>
        /// <param name="content">内容</param>
        /// <param name="attachmentlist">附件</param>
        /// <param name="isproxy">是否使用代理</param>
        /// <param name="msg">返回提示</param>
        /// <returns>返回ture or false 表示是否发送成功</returns>
        public static bool SendEmail(string toemailaddresslist, string ccaddresslist, string subject, string content, string attachmentlist, bool isproxy)
        {
            try
            {
                MailMessage Mail = new MailMessage();
                Mail.From = new MailAddress(From);
                string[] ToAddressList = toemailaddresslist.Split(';');
                for (int i = 0; i < ToAddressList.Length; i++)
                {
                    Mail.To.Add(new MailAddress(ToAddressList[i].ToString()));
                }
                Mail.BodyEncoding = System.Text.Encoding.UTF8;
                Mail.IsBodyHtml = true;

                //添加抄送人
                string[] List = ccaddresslist.Split(';');
                for (int i = 0; i < List.Length; i++)
                {
                    Mail.CC.Add(new MailAddress(List[i].ToString()));
                }

                Mail.Subject = subject;
                Mail.Body = content;

                //添加附件
                string[] AttachmentList = attachmentlist.Split(';');
                for (int i = 0; i < AttachmentList.Length; i++)
                {
                    Attachment att = new Attachment(AttachmentList[i].ToString());
                    ContentDisposition disposition = att.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(AttachmentList[i].ToString());
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(AttachmentList[i].ToString());
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(AttachmentList[i].ToString());
                    disposition.DispositionType = DispositionTypeNames.Attachment;
                    Mail.Attachments.Add(att);
                }

                if (isproxy)
                {
                    //还需要重写
                }

                SmtpClient client = new SmtpClient(SendServer);
                client.UseDefaultCredentials = false;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Credentials = new System.Net.NetworkCredential(From, Pwd);

                client.Send(Mail);
                return true;
            }
            catch (SmtpException ex)
            {
                throw new Exception("邮件发送失败\r\n" + ex.InnerException.Message);
            }
            catch (Exception ex)
            {
                throw new Exception("邮件发送失败\r\n" + ex.InnerException.Message);
            }

        }

        /// <summary>
        /// 发送邮件(自定义发件人)
        /// </summary>
        /// <param name="fromemailadd">发送箱地址</param>
        /// <param name="fromemailpwd">发件箱密码</param>
        /// <param name="toemailadd">收件人地址</param>
        /// <param name="cclist">抄送人地址</param>
        /// <param name="subject">主题</param>
        /// <param name="content">内容</param>
        /// <param name="attachmentlist">附件</param>
        /// <param name="isproxy">是否使用代理</param>
        /// <param name="msg">返回提示</param>
        /// <returns>返回ture or false 表示是否发送成功</returns>
        public static bool SendEmail(string fromemailadd, string fromemailpwd, string toemailaddresslist, string ccaddresslist, string subject, string content, string attachmentlist, bool isproxy)
        {
            try
            {
                MailMessage Mail = new MailMessage();
                Mail.From = new MailAddress(fromemailadd);
                string[] ToAddressList = toemailaddresslist.Split(';');
                for (int i = 0; i < ToAddressList.Length; i++)
                {
                    Mail.To.Add(new MailAddress(ToAddressList[i].ToString()));
                }
                Mail.BodyEncoding = System.Text.Encoding.UTF8;
                Mail.IsBodyHtml = true;

                //添加抄送人
                string[] List = ccaddresslist.Split(';');
                for (int i = 0; i < List.Length; i++)
                {
                    Mail.Bcc.Add(new MailAddress(List[i].ToString()));
                }


                Mail.Subject = subject;
                Mail.Body = content;


                //添加附件
                string[] AttachmentList = attachmentlist.Split(';');
                for (int i = 0; i < AttachmentList.Length; i++)
                {
                    Attachment Attachment = new Attachment(AttachmentList[i].ToString());
                    ContentDisposition disposition = Attachment.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(AttachmentList[i].ToString());
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(AttachmentList[i].ToString());
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(AttachmentList[i].ToString());
                    disposition.DispositionType = DispositionTypeNames.Attachment;
                    Mail.Attachments.Add(Attachment);
                }

                if (isproxy)
                {
                    //还需要重写
                }
                SmtpClient client = new SmtpClient(SendServer);
                client.UseDefaultCredentials = false;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Credentials = new System.Net.NetworkCredential(fromemailadd, fromemailpwd);

                client.Send(Mail);

                return true;
            }
            catch (SmtpException ex)
            {
                throw new Exception("邮件发送失败\r\n" + ex.InnerException.Message);
            }
            catch (Exception ex)
            {
                throw new Exception("邮件发送失败\r\n" + ex.InnerException.Message);
            }
        }

        #endregion

        #region  ReceiveEmail
        /// <summary>
        /// 下载服务器上的邮件到本地
        /// 返回Dictionary<int, OpenPop.Mime.Message> EmaiMessagelList字典
        /// </summary>
        public static Dictionary<string, Message> DownLoadEmail()
        {
            try
            {
                Pop3Client client = new Pop3Client();
                if (client.Connected)
                {
                    client.Disconnect();
                }
                client.Connect(ReceiveServer, 110, false);
                client.Authenticate(ReceiveAdd, ReceivePwd);
                EmailCount = client.GetMessageCount();
                EmaiMessagelList.Clear();

                for (int i = 1; i <= EmailCount; i++)
                {
                    Message message = client.GetMessage(i);
                    EmaiMessagelList.Add(client.GetMessageUid(i), message);
                }
                isDownLoad = true;
                return EmaiMessagelList;
            }
            catch (Exception ex)
            {
                EmaiMessagelList.Clear();
                throw new Exception("下载邮件失败\r\n" + ex.InnerException.Message);
            }
        }

        /// <summary>
        /// 获取邮件主题树结构
        /// </summary>
        /// <param name="EmailMessageList">下载的邮件</param>
        /// <returns></returns>
        public static System.Windows.Forms.TreeView GetEmailSubjectTree(Dictionary<string, Message> EmailMessageList)
        {
            System.Windows.Forms.TreeView SubjectTreeView = new System.Windows.Forms.TreeView();
            if (!isDownLoad)
            {
                throw new Exception("程序:邮件未下载");
            }
            {
                foreach (var dic in EmailMessageList)
                {
                    System.Windows.Forms.TreeNode Node = new System.Windows.Forms.TreeNode(dic.Value.Headers.Subject);
                    Node.Name = dic.Key.ToString();
                    SubjectTreeView.Nodes.Add(Node);
                }
                return SubjectTreeView;
            }

        }

        /// <summary>
        /// 获取下载邮件的主题列表
        /// </summary>
        /// <param name="EmailMessageList">下载的邮件</param>
        /// <returns></returns>
        public static string[] GetEmailSubjectList(Dictionary<string, Message> EmailMessageList)
        {
            string[] EmailSubjectList = new string[EmailMessageList.Count];
            if (!isDownLoad)
            {
                throw new Exception("程序:邮件未下载");
            }
            {
                foreach (var dic in EmailMessageList)
                {
                    int i = 0; EmailSubjectList[i] = dic.Value.Headers.Subject; i++;
                }
                return EmailSubjectList;
            }
        }

        /// <summary>
        /// 获取一个包含邮件信息的Message
        /// </summary>
        /// <param name="Number">邮件编号</param>
        /// <returns></returns>
        public static Message GetEmailMessage(string uid)
        {
            if (!isDownLoad)
            {
                throw new Exception("程序:邮件未下载");
            }
            {
                return EmaiMessagelList[uid];
            }
        }

        public static Email GetEmailInfo(Message message)
        {
            Email email = new Email();
            email.Subject = message.Headers.Subject;
            email.Fromaddress = message.Headers.Sender.ToString();
            string Toaddress = "";
            for (int i = 0; i < message.Headers.To.Count; i++)
            {
                Toaddress += message.Headers.To[i].Address + ";";
            }
            email.Toaddress = Toaddress.Substring(0, Toaddress.Length - 1);

            string Ccaddress = "";
            for (int i = 0; i < message.Headers.Cc.Count; i++)
            {
                Ccaddress += message.Headers.Cc[i].Address + ";";
            }
            email.Ccadress = Ccaddress.Substring(0, Ccaddress.Length - 1);

            string Bccaddress = "";
            for (int i = 0; i < message.Headers.Bcc.Count; i++)
            {
                Bccaddress += message.Headers.Bcc[i].Address + ";";
            }
            email.Bccadress = Bccaddress.Substring(0, Bccaddress.Length - 1);

            email.Senddate = message.Headers.DateSent.ToLocalTime().ToString("yyyy-MM-dd hh:mm:ss");

            if (!message.MessagePart.IsMultiPart)
            {
                email.Content = Encoding.Default.GetString(message.MessagePart.Body);
            }
            else
            {
                for (int i = 0; i < message.MessagePart.MessageParts.Count; i++)
                {
                    email.Content += Encoding.Default.GetString(message.MessagePart.MessageParts[i].Body);
                }
            }
            if (!message.MessagePart.IsAttachment)
            {
                email.Attachments = null;
            }
            else
            {

            }
            return email;
        }

        /// <summary>
        /// 获取邮件数量
        /// </summary>
        /// <returns></returns>
        public static int GetMessagesCount()
        {
            Pop3Client client = new Pop3Client();
            if (client.Connected)
            {
                client.Disconnect();
            }
            client.Connect(ReceiveServer, 110, false);
            client.Authenticate(ReceiveAdd, ReceivePwd);
            return client.GetMessageCount();
        }

        #endregion
    }

    public class Email
    {
        private string subject;
        private string fromaddress;
        private string toaddress;
        private string ccadress;
        private string bccadress;
        private string senddate;
        private string content;


        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }
        public string Fromaddress
        {
            get { return fromaddress; }
            set { fromaddress = value; }
        }
        public string Toaddress
        {
            get { return toaddress; }
            set { toaddress = value; }
        }
        public string Ccadress
        {
            get { return ccadress; }
            set { ccadress = value; }
        }
        public string Bccadress
        {
            get { return bccadress; }
            set { bccadress = value; }
        }
        public string Senddate
        {
            get { return senddate; }
            set { senddate = value; }
        }
        public string Content
        {
            get { return content; }
            set { content = value; }
        }

        public Dictionary<string, string> Attachments = new Dictionary<string, string>();

    }

    class BuilderTrees
    {
        public BuilderTrees()
        { }

        public static System.Windows.Forms.TreeNode BuildTree(Message message, int i)
        {
            System.Windows.Forms.TreeNode child = new System.Windows.Forms.TreeNode();
            System.Windows.Forms.TreeNode TopNode = new System.Windows.Forms.TreeNode(message.Headers.Subject, new[] { child });
            TopNode.Tag = i;
            return TopNode;
        }


        private System.Windows.Forms.TreeNode BuildChild(MessagePart messagepart)
        {
            System.Windows.Forms.TreeNode[] child = new System.Windows.Forms.TreeNode[0];

            if (messagepart.IsMultiPart)
            {
                child = new System.Windows.Forms.TreeNode[messagepart.MessageParts.Count];
                for (int i = 0; i < messagepart.MessageParts.Count; i++)
                {
                    child[i] = BuildChild(messagepart.MessageParts[i]);
                }
            }
            System.Windows.Forms.TreeNode currentNode = new System.Windows.Forms.TreeNode(messagepart.ContentType.MediaType, child);
            currentNode.Tag = messagepart;
            return currentNode;
        }


    }

}
View Code

ExcelHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Collections;
using NPOI.HSSF.Util;
using NPOI.XSSF.UserModel;

///
///使用该类 需要添加 NOPI.dll 的引用
///版本为 2.0.0.0 
namespace Common
{
    public static class ExcelHelper
    {
        #region  导出

        /// <summary>
        /// 导出一个Datatable的数据到Excel文件
        /// </summary>
        /// <param name="dt">需要导出的DataTable</param>
        public static void ExportDataTableToExcel(DataTable dt)
        {
            ExportDataTableToExcel(dt, "");
        }

        /// <summary>
        /// 导出一个Datatable的数据到Excel文件
        /// </summary>
        /// <param name="dt">需要导出的DataTable</param>
        /// <param name="sheetname">需要保存的Sheet名称</param>
        public static void ExportDataTableToExcel(DataTable dt, string sheetname)
        {
            try
            {
                HSSFWorkbook wk = new HSSFWorkbook();
                ISheet sheet = null;
                if (string.IsNullOrEmpty(sheetname))
                {
                    sheet = wk.CreateSheet("Sheet1");
                }
                else
                {
                    sheet = wk.CreateSheet(sheetname);
                }
                int RowCount = dt.Rows.Count;
                int ColumnCount = dt.Columns.Count;


                IRow row = sheet.CreateRow(0);
                for (int j = 0; j < ColumnCount; j++) //列标题
                {
                    sheet.SetColumnWidth(j, 20 * 256);
                    ICell cell = row.CreateCell(j);
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(dt.Columns[j].ColumnName);
                }

                for (int i = 0; i < RowCount; i++)
                {
                    row = sheet.CreateRow(i + 1);

                    for (int j = 0; j < ColumnCount; j++)
                    {
                        sheet.SetColumnWidth(j, 20 * 256);
                        ICell cell = row.CreateCell(j);
                        cell.SetCellType(CellType.String);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }

                }

                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Execl files (*.xls)|*.xls";
                dlg.FilterIndex = 0;
                dlg.RestoreDirectory = true;
                dlg.CreatePrompt = true;
                dlg.Title = "保存为Excel文件";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    using (FileStream fs = File.OpenWrite(dlg.FileName)) //打开一个xls文件,如果没有则自行创建,如果存在文件则在创建是不要打开该文件!
                    {
                        wk.Write(fs);   //向打开的这个xls文件中写入Sheet1表并保存。
                        MessageBox.Show("导出成功!");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("导出失败\r\n" + ex.InnerException.Message);
            }
        }

        /// <summary>
        /// 导出一个DataGridView的数据到Excel文件
        /// </summary>
        /// <param name="Gridview">绑定了数据源的DataGridView控件</param>
        public static void ExportDataGridViewToExcel(DataGridView Gridview)
        {
            ExportDataGridViewToExcel(Gridview, "");
        }

        /// <summary>
        /// 导出一个DataGridView的数据到Excel文件
        /// </summary>
        /// <param name="Gridview">绑定了数据源的DataGridView控件</param>
        /// <param name="sheetname">需要保存的Sheet名称</param>
        public static void ExportDataGridViewToExcel(DataGridView Gridview, string sheetname)
        {
            try
            {
                HSSFWorkbook wk = new HSSFWorkbook();
                ISheet sheet = null;
                if (string.IsNullOrEmpty(sheetname))
                {
                    sheet = wk.CreateSheet("Sheet1");
                }
                else
                {
                    sheet = wk.CreateSheet(sheetname);
                }
                int RowCount = Gridview.RowCount;
                int ColumnCount = Gridview.ColumnCount;

                IRow row = sheet.CreateRow(0);
                for (int j = 0; j < ColumnCount; j++) //列标题
                {
                    sheet.SetColumnWidth(j, 20 * 256);
                    ICell cell = row.CreateCell(j);
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(Gridview.Columns[j].HeaderText);
                    cell.CellStyle = GetCellStyle(wk, Styles.ColumnHead);
                }

                for (int i = 0; i < RowCount; i++)
                {
                    row = sheet.CreateRow(i + 1);

                    for (int j = 0; j < ColumnCount; j++)
                    {
                        sheet.SetColumnWidth(j, 20 * 256);
                        ICell cell = row.CreateCell(j);
                        cell.SetCellType(CellType.String);
                        cell.SetCellValue(Gridview.Rows[i].Cells[j].Value.ToString());
                    }

                }

                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Execl files (*.xls)|*.xls";
                dlg.FilterIndex = 0;
                dlg.RestoreDirectory = true;
                dlg.CreatePrompt = true;
                dlg.Title = "保存为Excel文件";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    using (FileStream fs = File.OpenWrite(dlg.FileName)) //打开一个xls文件,如果没有则自行创建,如果存在文件则在创建是不要打开该文件!
                    {
                        wk.Write(fs);   //向打开的这个xls文件中写入Sheet1表并保存。
                        MessageBox.Show("导出成功!");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("导出失败\r\n" + ex.InnerException.Message);
            }
        }

        #endregion

        #region 读取

        /// <summary>
        /// 读取一个Excel文件(只读取该文件的第一个Sheet的数据,不指定读取的列范围)
        /// </summary>
        /// <returns>返回一个包含Excel文件数据的DataTable</returns>
        public static DataTable ReadExcelFirstSheetToDataTable()
        {
            return ReadExcelFirstSheetToDataTable("", "");
        }

        /// <summary>
        /// 读取一个Excel文件(只读取该文件的第一个Sheet的数据,指定从startcolumnname列开始,endcolumnname列结束的范围内的数据)
        /// </summary>
        /// <param name="startcolumnname">开始列名称</param>
        /// <param name="endcolumnname">结束列名称</param>
        /// <returns>返回一个包含Excel文件数据的DataTable</returns>
        public static DataTable ReadExcelFirstSheetToDataTable(string startcolumnname, string endcolumnname)
        {

            DataTable dt = new DataTable();
            OpenFileDialog OpenDialog = new OpenFileDialog();
            OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx";
            OpenDialog.FilterIndex = 0;
            OpenDialog.RestoreDirectory = true;
            OpenDialog.Title = "读取Excel文件";

            OleDbConnection con;
            OleDbDataAdapter da;
            DataSet ds = new DataSet();

            if (OpenDialog.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(OpenDialog.FileName))
                {
                    MessageBox.Show("请选择Excel文件!");
                    return dt;
                }
                else
                {
                    try
                    {
                        string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.'));
                        string connStr = "";
                        switch (filename)
                        {
                            case ".xls":
                                {
                                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                                    break;
                                }
                            case ".xlsx":
                                {
                                    connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                                    break;
                                }
                            default:
                                {
                                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                                    break;

                                }
                        }
                        string sql = "";
                        if (!string.IsNullOrEmpty(startcolumnname) && !string.IsNullOrEmpty(endcolumnname))
                        {
                            sql = "SELECT * FROM [" + GetExcelFirstTableName(OpenDialog.FileName, connStr)[0].ToString() + startcolumnname + ":" + endcolumnname + "]  ";
                        }
                        else
                        {
                            sql = "SELECT * FROM [" + GetExcelFirstTableName(OpenDialog.FileName, connStr)[0].ToString() + "]  ";
                        }
                        con = new OleDbConnection(connStr);
                        con.Open();
                        da = new OleDbDataAdapter(sql, con);
                        da.Fill(ds);
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            MessageBox.Show("选择的文件没数据!"); return dt;
                        }
                        else
                        {
                            dt = ds.Tables[0];
                        }
                        return dt;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("读取Excel文件失败\r\n" + ex.InnerException.Message);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 读取一个Excel文件(读取该文件的所有Sheet的数据,但是该文件的所有Sheet数据格式必须一致,不限制列范围)
        /// </summary>
        /// <returns>返回一个包含Excel文件数据的DataTable</returns>
        public static DataTable ReadMoreSameExcelToDataTable()
        {
            return ReadMoreSameExcelToDataTable("", "");
        }

        /// <summary>
        /// 读取一个Excel文件(读取该文件的所有Sheet的数据,但是该文件的所有Sheet数据格式必须一致,限制列范围从startcolumnname到endcolumnname)
        /// </summary>
        /// <param name="startcolumnname">开始列名称</param>
        /// <param name="endcolumnname">结束列名称</param>
        /// <returns>返回一个包含Excel文件数据的DataTable</returns>
        public static DataTable ReadMoreSameExcelToDataTable(string startcolumnname, string endcolumnname)
        {
            DataTable dt = new DataTable();
            OpenFileDialog OpenDialog = new OpenFileDialog();
            OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx";
            OpenDialog.FilterIndex = 0;
            OpenDialog.RestoreDirectory = true;
            OpenDialog.Title = "读取Excel文件";

            OleDbConnection con;
            OleDbDataAdapter da;
            DataSet ds = new DataSet();

            if (OpenDialog.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(OpenDialog.FileName))
                {
                    MessageBox.Show("请选择Excel文件!");
                    return dt;
                }
                else
                {
                    try
                    {
                        string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.'));
                        string connStr = "";
                        switch (filename)
                        {
                            case ".xls":
                                {
                                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                                    break;
                                }
                            case ".xlsx":
                                {
                                    connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                                    break;
                                }
                            default:
                                {
                                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                                    break;

                                }
                        }
                        ArrayList sqllist = new ArrayList();
                        ArrayList tablelist = new ArrayList();
                        tablelist = GetExcelAllTableName(OpenDialog.FileName, connStr);
                        if (!string.IsNullOrEmpty(startcolumnname) && !string.IsNullOrEmpty(endcolumnname))
                        {
                            for (int i = 0; i < tablelist.Count; i++)
                            {
                                sqllist.Add("SELECT  * FROM [" + tablelist[i] + startcolumnname + ":" + endcolumnname + "]");
                            }
                        }
                        else
                        {
                            for (int i = 0; i < tablelist.Count; i++)
                            {
                                sqllist.Add("SELECT  * FROM [" + tablelist[i] + "]");
                            }
                        }
                        con = new OleDbConnection(connStr);
                        con.Open();
                        for (int i = 0; i < sqllist.Count; i++)
                        {
                            da = new OleDbDataAdapter(sqllist[i].ToString(), con);
                            da.Fill(ds);
                        }
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            MessageBox.Show("选择的文件没数据!");
                            return dt;
                        }
                        else
                        {
                            dt = ds.Tables[0];
                        }
                        return dt;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("读取Excel文件失败\r\n" + ex.InnerException.Message);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 读取一个Excel文件(读取该文件的所有Sheet的数据,该文件的Sheet数据格式可以一致)
        /// </summary>
        /// <returns>返回一个包含Excel文件数据的DataSet</returns>
        public static DataSet ReadMoreNotSameExcelToDataTable()
        {
            DataTable dt = new DataTable();
            OpenFileDialog OpenDialog = new OpenFileDialog();
            OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx";
            OpenDialog.FilterIndex = 0;
            OpenDialog.RestoreDirectory = true;
            OpenDialog.Title = "读取Excel文件";

            OleDbConnection con;
            OleDbDataAdapter da;
            DataSet ds = new DataSet();

            if (OpenDialog.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(OpenDialog.FileName))
                {
                    MessageBox.Show("请选择Excel文件!");
                    return ds;
                }
                else
                {
                    try
                    {
                        string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.'));
                        string connStr = "";
                        switch (filename)
                        {
                            case ".xls":
                                {
                                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                                    break;
                                }
                            case ".xlsx":
                                {
                                    connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                                    break;
                                }
                            default:
                                {
                                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                                    break;

                                }
                        }
                        ArrayList sqllist = new ArrayList();
                        ArrayList tablelist = new ArrayList();
                        tablelist = GetExcelAllTableName(OpenDialog.FileName, connStr);
                        for (int i = 0; i < tablelist.Count; i++)
                        {
                            sqllist.Add("SELECT  * FROM [" + tablelist[i] + "]");
                        }
                        con = new OleDbConnection(connStr);
                        con.Open();
                        for (int i = 0; i < sqllist.Count; i++)
                        {
                            da = new OleDbDataAdapter(sqllist[i].ToString(), con);
                            da.Fill(ds, "Table" + i);
                        }
                        bool isHave = false;
                        for (int i = 0; i < ds.Tables.Count; i++)
                        {
                            if (ds.Tables[i].Rows.Count != 0)
                            {
                                isHave = true;
                            }
                        }
                        if (!isHave)
                        {
                            MessageBox.Show("选择的文件没数据!"); return ds;
                        }
                        return ds;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("读取Excel文件失败\r\n" + ex.InnerException.Message);
                    }
                }
            }
            return ds;
        }

        /// <summary>
        /// 获取第一个Sheet的名称
        /// </summary>
        /// <param name="excelFileName">Excel文件名称</param>
        /// <param name="strExtension">读取Excel文件数据的数据连接</param>
        /// <returns></returns>
        private static ArrayList GetExcelFirstTableName(string excelFileName, string strExtension)
        {

            ArrayList tablenamelist = new ArrayList();
            try
            {
                if (File.Exists(excelFileName))
                {
                    using (OleDbConnection conn = new OleDbConnection(strExtension))
                    {
                        conn.Open();
                        DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        tablenamelist.Add(dt.Rows[0][2].ToString().Trim());
                        return tablenamelist;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            return tablenamelist;

        }

        /// <summary>
        /// 获取所有Sheet的名称
        /// </summary>
        /// <param name="excelFileName">Excel文件名称</param>
        /// <param name="strExtension">读取Excel文件数据的数据连接</param>
        /// <returns></returns>
        private static ArrayList GetExcelAllTableName(string excelFileName, string strExtension)
        {

            ArrayList tablenamelist = new ArrayList();
            try
            {
                if (File.Exists(excelFileName))
                {
                    using (OleDbConnection conn = new OleDbConnection(strExtension))
                    {
                        conn.Open();
                        DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            tablenamelist.Add(dt.Rows[i][2].ToString().Trim());
                        }
                        return tablenamelist;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            return tablenamelist;

        }
        #endregion

        #region  //其他

        private enum Styles
        {
            /// <summary>
            /// 列头
            /// </summary>
            ColumnHead,
            /// <summary>
            /// 行头
            /// </summary>
            RowHead,
            /// <summary>
            /// 货币
            /// </summary>
            Money,
            /// <summary>
            /// 时间
            /// </summary>
            DateTime
        }


        private static ICellStyle GetCellStyle(HSSFWorkbook wk, Styles style)
        {
            ICellStyle CellStyle = wk.CreateCellStyle();
            CellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中显示

            switch (style)
            {
                case Styles.ColumnHead:
                    CellStyle.FillPattern = FillPattern.Squares;
                    CellStyle.FillForegroundColor = CellStyle.FillBackgroundColor = HSSFColor.Yellow.Index;
                    break;
                case Styles.RowHead:
                    CellStyle.FillPattern = FillPattern.Squares;
                    CellStyle.FillForegroundColor = CellStyle.FillBackgroundColor = HSSFColor.Yellow.Index;
                    break;
                case Styles.DateTime:
                    IDataFormat DateFormat = wk.CreateDataFormat();
                    CellStyle.DataFormat = DateFormat.GetFormat("yyyy-MM-dd"); ;
                    break;
                case Styles.Money:
                    IDataFormat MoneyFormat = wk.CreateDataFormat();
                    CellStyle.DataFormat = MoneyFormat.GetFormat("¥#,##0");
                    break;
            }
            return CellStyle;
        }

        #endregion

        #region Write Excel Template

        /// <summary>
        /// 按照Excel模板格式导出数据
        /// </summary>
        /// <param name="dtsources">要导出的数据DataTable</param>
        /// <param name="templatepath">模板路径</param>
        /// <param name="destpath">保存Excel文件的路径</param>
        /// <param name="startrowindex">开始写入的行索引 默认为1</param>
        /// <param name="startcolumnindex">开始写入的列索引 默认为1</param>
        public static void WriteExcelTemplate(DataTable dtsources, string templatepath, string destpath, int startrowindex, int startcolumnindex)
        {
            if (string.IsNullOrEmpty(templatepath)) throw new Exception("模板路径不正确");
            if (string.IsNullOrEmpty(destpath)) throw new Exception("存储路径不能为空");
            XSSFWorkbook wb = null;

            FileStream fileStream = new FileStream(templatepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            FileStream fileStream2 = null;
            try
            {
                wb = new XSSFWorkbook(fileStream);

                ISheet sheet = wb.GetSheetAt(0);
                IRow row1 = sheet.GetRow(1);
                ICell cell1 = row1.GetCell(1);
                string s = cell1.StringCellValue;

                for (int i = 0; i < dtsources.Rows.Count; i++)
                {
                    if (i < 2)
                    {
                        IRow row = sheet.GetRow(startrowindex + i);
                        if (row == null)
                        {
                            row = sheet.CreateRow(startrowindex + i);
                        }
                        for (int j = 0; j < dtsources.Columns.Count; j++)
                        {
                            ICell cell = row.GetCell(startcolumnindex + j); //
                            if (cell == null)
                            {
                                cell = row.CreateCell(startcolumnindex + j);
                            }
                            cell.SetCellType(CellType.String);
                            cell.SetCellValue(dtsources.Rows[i][j].ToString());
                        }
                    }
                }
                fileStream2 = new FileStream(destpath, FileMode.Create, FileAccess.ReadWrite);
                wb.Write(fileStream2);
            }
            catch (Exception ex)
            {
                throw new Exception("\r\n" + ex.InnerException.Message);
            }
            finally
            {
                fileStream.Close();
                fileStream2.Close();
            }
        }

        #endregion

    }
}
View Code

SocketHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Common
{
    public class SocketHelper
    {
        public delegate void ShowMessageDelagate(string ip, string msg);

        /// <summary>
        /// ShowMessageDelagate类型的event 将委托参数传送出去
        /// </summary>
        public event ShowMessageDelagate OnShowMessage;

        private int iPort = 8080;
        private int oPort = 8081;
        private string oIP = "";
        private string rIP = "";
        private string iMessage = "";


        /// <summary>
        /// 通过需要发送到的IP构造SocketHelper对象 将使用默认接收端口为8080 发送端口为8081
        /// </summary>
        /// <param name="oip">需要发送到的IP</param>
        public SocketHelper(string oip)
        {
            this.oIP = oip;
        }

        /// <summary>
        /// 通过接收端口,发送端口和需要发送到的IP构造SocketHelper对象
        /// </summary>
        /// <param name="iport">接收端口</param>
        /// <param name="oport">发送端口</param>
        /// <param name="oip">需要发送到的IP</param>
        public SocketHelper(int iport, int oport, string oip)
        {
            this.iPort = iport;
            this.oPort = oport;
            this.oIP = oip;
        }

        #region  接受消息

        /// <summary>
        /// 开始监听本机 默认监听8080端口
        /// </summary>
        public void StartListener()
        {
            Thread ListenThread = new Thread(new ThreadStart(ReceiveMessage));
            ListenThread.Name = "ListenThread";
            ListenThread.IsBackground = true;
            ListenThread.Start();
        }

        private void ReceiveMessage()
        {
            // IPAddress LocalIP = Dns.GetHostAddresses(Dns.GetHostName()).Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).First();
            TcpListener tcpListener = new TcpListener(IPAddress.Any, iPort); //
            tcpListener.Start();
            while (true)
            {
                TcpClient ListenerClient = tcpListener.AcceptTcpClient();
                NetworkStream stream = ListenerClient.GetStream();
                StreamReader reader = new StreamReader(stream);
                iMessage = reader.ReadToEnd();
                rIP = ListenerClient.Client.RemoteEndPoint.ToString();
                stream.Close();
                reader.Close();
                ListenerClient.Close();
                if (OnShowMessage != null)
                {
                    OnShowMessage(rIP, iMessage);
                }
            }
        }

        #endregion

        #region 发送消息

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg">要发送的消息 默认为UTF8编码</param>
        /// <returns></returns>
        public bool SendMessage(string msg)
        {
            return SendMessage(msg, null);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg">要发送的消息 </param>
        /// <param name="encoding">要使用的编码</param>
        /// <returns></returns>
        public bool SendMessage(string msg, Encoding encoding)
        {
            if (string.IsNullOrEmpty(oIP))
            {
                return false;
            }
            else
            {
                TcpClient Client = null;
                NetworkStream stream = null;
                try
                {
                    Client = new TcpClient();
                    Client.Connect(oIP, oPort);
                    stream = Client.GetStream();

                    if (encoding == null)
                    {
                        byte[] bytes = Encoding.UTF8.GetBytes(msg);
                        int i = 0;
                        while (i < bytes.Length)
                        {
                            stream.WriteByte(bytes[i]);
                            i++;
                        }
                    }
                    else
                    {
                        byte[] bytes = encoding.GetBytes(msg);
                        int i = 0;
                        while (i < bytes.Length)
                        {
                            stream.WriteByte(bytes[i]);
                            i++;
                        }
                    }
                    return true;
                }
                catch (SocketException ex)
                {
                    throw new Exception("发送失败\r\nSocketException:" + ex.Message);
                }
                catch (Exception ex)
                {
                    throw new Exception("发送失败\r\n" + ex.Message);
                }
                finally
                {
                    if (stream != null) { stream.Close(); }
                    if (Client != null) { Client.Close(); }

                }
            }
        }

        #endregion
    }
}
View Code

SqlHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace Common
{
    public static class SqlHelpers
    {
        /// <summary>
        /// 数据库连接串
        /// </summary>
        private static SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());

        /// <summary>
        /// 打开或者关闭数据库连接
        /// </summary>
        private static void ConnectionStateChange()
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            else
            {
                connection.Close();
            }

        }

        #region SQL语句

        /// <summary>
        /// 查询是否包含某一满足条件的记录
        /// </summary>
        /// <param name="Querystr">SQL语句字符串</param>
        /// <returns>包含返回;true 不包含则返回:false</returns>
        public static bool IsHaveRecord(string Querystr)
        {
            return isHaveRecord(Querystr, null);
        }

        /// <summary>
        /// 查询是否包含某一满足条件的记录(带参数)
        /// </summary>
        /// <param name="QueryStr">SQL语句字符串</param>
        /// <param name="ParameterList">参数数组</param>
        /// <returns>包含返回;true 不包含则返回:false</returns>
        public static bool isHaveRecord(string QueryStr, params SqlParameter[] ParameterList)
        {
            try
            {
                SqlCommand cmd = new SqlCommand(QueryStr);
                ConnectionStateChange();
                if (ParameterList != null)
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = QueryStr;
                    cmd.Parameters.AddRange(ParameterList);
                }
                else
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = QueryStr;
                }
                return cmd.ExecuteReader().Read() == true ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }

        /// <summary>
        /// 获取查询结果集
        /// </summary>
        /// <param name="QueryStr">SQL语句字符串</param>
        /// <returns>返回一个DataTable</returns>
        public static DataTable ExecuteDataTable(string QueryStr)
        {
            return ExecuteDataTable(QueryStr, null);
        }

        /// <summary>
        /// 获取查询结果集
        /// </summary>
        /// <param name="QueryStr">SQL语句字符串</param>
        /// <param name="ParameterList">参数数组</param>
        /// <returns>返回一个DataTable</returns>
        public static DataTable ExecuteDataTable(string QueryStr, params SqlParameter[] ParameterList)
        {
            try
            {
                DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand();
                ConnectionStateChange();
                if (ParameterList != null)
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = QueryStr;
                    cmd.Parameters.AddRange(ParameterList);
                }
                else
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = QueryStr;
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="QueryStr">SQL语句</param>
        /// <returns>受影响行数大于0返回true 否则返回 false</returns>
        public static bool ExecuteNonQuery(string QueryStr)
        {
            return ExecuteNonQuery(QueryStr, null);
        }

        /// <summary>
        /// 执行带参数的SQL语句
        /// </summary>
        /// <param name="QueryStr">SQL语句</param>
        /// <param name="ParameterList">SqlParameter参数数组</param>
        /// <returns>受影响行数大于0返回true 否则返回 false</returns>
        public static bool ExecuteNonQuery(string QueryStr, params SqlParameter[] ParameterList)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                ConnectionStateChange();
                if (ParameterList != null)
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = QueryStr;
                    cmd.Parameters.AddRange(ParameterList);
                }
                else
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = QueryStr;
                }
                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }

        /// <summary>
        /// 执行多条SQL语句
        /// </summary>
        /// <param name="QueryStrList">SQL语句字符串数组</param>
        /// <returns>返回所有SQL语句执行所影响的行数综合</returns>
        public static bool ExecuteNonQueryNotSingle(string[] QueryStrList)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                ConnectionStateChange();

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = PrepareNotSingleSQL(QueryStrList);

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }


        private static string PrepareNotSingleSQL(string[] QueryStrList)
        {
            string sql = "";
            foreach (string str in QueryStrList)
            {
                sql += str + ";";
            }
            return sql;
        }

        #endregion


        #region 存储过程


        /// <summary>
        /// 查询是否包含某一满足条件的记录
        /// </summary>
        /// <param name="Querystr">存储过程</param>
        /// <returns>包含返回;true 不包含则返回:false</returns>
        public static bool isProHaveRecord(string ProName)
        {
            return isProHaveRecord(ProName, null);
        }

        /// <summary>
        /// 查询是否包含某一满足条件的记录(带参数)
        /// </summary>
        /// <param name="QueryStr">存储过程</param>
        /// <param name="ParameterList">参数数组</param>
        /// <returns>包含返回;true 不包含则返回:false</returns>
        public static bool isProHaveRecord(string ProName, params SqlParameter[] ParameterList)
        {
            try
            {
                SqlCommand cmd = new SqlCommand(ProName);
                ConnectionStateChange();
                if (ParameterList != null)
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = ProName;
                    cmd.Parameters.AddRange(ParameterList);
                }
                else
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = ProName;
                }
                return cmd.ExecuteReader().Read() == true ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }

        /// <summary>
        /// 获取查询结果集
        /// </summary>
        /// <param name="QueryStr">存储过程</param>
        /// <returns>返回一个DataTable</returns>
        public static DataTable ExecuteProDataTable(string ProName)
        {
            return ExecuteDataTable(ProName, null);
        }

        /// <summary>
        /// 获取查询结果集
        /// </summary>
        /// <param name="QueryStr">存储过程</param>
        /// <param name="ParameterList">SqlParameter参数数组</param>
        /// <returns>返回一个DataTable</returns>
        public static DataTable ExecuteProDataTable(string ProName, params SqlParameter[] ParameterList)
        {
            try
            {
                DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand();
                ConnectionStateChange();
                if (ParameterList != null)
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = ProName;
                    cmd.Parameters.AddRange(ParameterList);
                }
                else
                {
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = ProName;
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="QueryStr">存储过程名称</param>
        /// <returns>受影响行数大于0返回true 否则返回 false</returns>
        public static bool ExecuteProNonQuery(string ProName)
        {
            return ExecuteProNonQuery(ProName, null);
        }

        /// <summary>
        /// 执行带参数的存储过程
        /// </summary>
        /// <param name="QueryStr">存储过程</param>
        /// <param name="ParameterList">SqlParameter参数数组</param>
        /// <returns>受影响行数大于0返回true 否则返回 false</returns>
        public static bool ExecuteProNonQuery(string ProName, params SqlParameter[] ParameterList)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                ConnectionStateChange();
                if (ParameterList != null)
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = ProName;
                    cmd.Parameters.AddRange(ParameterList);
                }
                else
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = ProName;
                }
                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ConnectionStateChange();
            }
        }

        #endregion

        #region  Insert DataTable To DB

        /// <summary>
        /// 把DataTable的数据写入数据库(DataTable的数据列的顺序必须与数据库表的列顺序相同)
        /// </summary>
        /// <param name="dt">需要写入的DataTable</param>
        /// <param name="DestinationTableName">被写入的数据库中的表名称</param>
        public static void InsertDatableToDB(DataTable dt, string DestinationTableName)
        {
            using (SqlBulkCopy sqlBC = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["conn"].ToString(), SqlBulkCopyOptions.UseInternalTransaction))
            {
                sqlBC.BatchSize = 100;
                sqlBC.NotifyAfter = 1;
                sqlBC.DestinationTableName = DestinationTableName;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sqlBC.ColumnMappings.Add(i, i);//(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
                }
                sqlBC.WriteToServer(dt);
            }
        }

        #endregion
    }
}
View Code

 

以上代码中用到的DLL在这里下载:下载

转载于:https://www.cnblogs.com/ShuiMu/articles/3831752.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python语音助手是一个能够接收语音输入并进行文字识别、聊天回复、文字合成为语音并播放的应用程序。实现一个Python语音助手的过程可以分为以下几个步骤: 1. 语音转文字:使用百度AI开放平台的语音识别API,将音频文件转换为文字。可以使用FFmpeg工具将音频格式转换为API支持的格式。 2. 聊天接口:使用图灵机器人接口,将用户的文字输入发送给机器人,获取机器人的回复。 3. 文字转语音:使用讯飞开放平台的语音合成API,将机器人的回复文字转换为语音文件。 4. 播放语音:使用pyaudio模块录制和播放音频,将语音文件播放出来。 下面是一个简单的Python语音助手的代码示例: ``` from aip import AipSpeech import pyaudio import wave import requests import json # 初始化百度语音识别的API APP_ID = '25016634' API_KEY = 'Qsj6XGf0m1ilsV0QwLTmHeiy' SECRET_KEY = 'Mctl1jHY85Hr3wmTpizLI********' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) # 录音函数 def record_audio(): # 使用pyaudio录制音频 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 RECORD_SECONDS = 5 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("* recording") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) print("* done recording") stream.stop_stream() stream.close() p.terminate() # 保存录音文件 wf = wave.open("record.wav", 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() # 语音转文字函数 def speech_to_text(): # 读取录音文件 with open("record.wav", 'rb') as f: data = f.read() # 调用百度语音识别API,将音频文件转为文字 result = client.asr(data, 'wav', 16000, { 'dev_pid': 1536, }) # 提取识别结果 if 'result' in result.keys(): text = result['result'][0] else: text = "" return text # 聊天函数 def chat(text): # 调用图灵机器人接口,进行文字聊天 url = 'http://openapi.tuling123.com/openapi/api/v2' data = { "reqType": 0, "perception": { "inputText": { "text": text } }, "userInfo": { "apiKey": "YOUR_API_KEY", "userId": "YOUR_USER_ID" } } response = requests.post(url, json=data) result = json.loads(response.text) # 提取机器人的回复 reply = result['results'][0]['values']['text'] return reply # 文字转语音函数 def text_to_speech(text): # 调用讯飞开放平台的语音合成API,将文字转为语音文件 # 这里省略具体代码 # 返回生成的语音文件路径 return "speech.wav" # 播放语音函数 def play_audio(file_path): # 使用pyaudio播放音频 CHUNK = 1024 wf = wave.open(file_path, 'rb') p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(CHUNK) while data: stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate() # 主函数 def main(): # 录音 record_audio() # 语音转文字 text = speech_to_text() # 聊天 reply = chat(text) # 文字转语音 speech_file = text_to_speech(reply) # 播放语音 play_audio(speech_file) # 运行主函数 if __name__ == '__main__': main() ``` 这段代码实现了一个基本的Python语音助手,可以录制音频文件,并将其转换为文字,然后发送给机器人进行聊天回复,最后将回复的文字转换为语音并播放出来。需要注意的是,其中的一些API的调用需要替换为你自己的API Key和Secret Key。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [小白如何做一个Python人工智能语音助手](https://blog.csdn.net/m0_57307642/article/details/120849915)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [简易语音助手—python](https://blog.csdn.net/chqhong/article/details/112427268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值