c# 讀取 excel文件內容,寫入txt文檔

1 winform 讀取excel文檔數據庫

1)點擊button按鈕,彈出上傳excel窗口ide

private  void button_headcompany_Click(object sender, EventArgs e)
        {
            string HeadCompany_rowValue = HeadCompany_row.Text;
            string HeadCompany_columnValue = HeadCompany_column.Text;
            if (string.IsNullOrEmpty(HeadCompany_rowValue) || string.IsNullOrEmpty(HeadCompany_columnValue))
            {
                MessageBox.Show("請填寫行和列的值,例如 行A5 列BB", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ButtonClick("總公司彙總", HeadCompany_rowValue, HeadCompany_columnValue);            
        }

  

2)判斷是否上傳的文檔格式是否正常 xls和xlsx類型的文檔lua

public static void ButtonClick(string SheetType,string rowValue,string ColumnValue)
        {
            string worksheetname = string.Empty;
            string filepath = "";
            //導入本地文件  
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "文檔(*.xls)|*.xls|文檔(*.xlsx)|*.xlsx";
            if (file.ShowDialog() == DialogResult.OK) filepath = file.FileName;
            string fileNameWithoutExtension = System.IO.Path.GetDirectoryName(filepath);// 沒有擴展名的文件名 「Default」
            //判斷有沒有文件導入  
            if (file.FileName.Length == 0)
            {
                MessageBox.Show("請選擇要導入的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ////改變了原來的邏輯,直接從中間表導出數據Excel,ADDBYxingkai  
            // dt = Liveflow.HaiKang.ExcelHelper.ExcelToDataTable(filePath, 1, 27, -1, 0, 1);
            //把excel表數據讀取到DataTable中
            string strConn = string.Empty;
            string excelName = SheetType;
            //注意:把一個excel文件看作一個數據庫,一個sheet看作一張表。語法 "SELECT * FROM [sheet1$]",表單要使用"[]"和"$"
            // 一、HDR表示要把第一行做爲數據仍是做爲列名,做爲數據用HDR=no,做爲列名用HDR=yes;
            // 二、經過IMEX=1來把混合型做爲文本型讀取,避免null值。
            // 三、判斷是xls仍是xlsx
            string[] sArray = filepath.Split('.');
            if (sArray[1].ToString() == "xls")
            {
                //  strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1';";
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"; // Office 07及以上版本 不能出現多餘的空格 並且分號注意
                //dt = HRManageXls(strConn, excelName, SheetType, fileNameWithoutExtension, rowValue, ColumnValue);
            }
            else if (sArray[1].ToString() == "xlsx")
            {
                strConn = "Provider=Microsoft.Ace.OleDb.12.0;data source='" + filepath + "';Extended Properties='Excel 12.0; HDR=NO; IMEX=1';";
                HRManageXlsX(strConn, excelName, SheetType, fileNameWithoutExtension, rowValue, ColumnValue);
            }
        }

  

3)讀取excel文檔中的數據 轉換爲datatable日誌

public static void  HRManageXlsX(string strConn, string excelName,string SheetType,string fileNameWithoutExtension, string rowValue, string ColumnValue)
        {
            DataTable dt = new DataTable();
            dt=GetCsvToDataTable(strConn, excelName, SheetType,rowValue, ColumnValue);//獲取excel數據
            //指定源列和目標列之間的對應關係
            int row = dt.Rows.Count;//exce數據總行
            int col = dt.Columns.Count;//excel數據總列
            //生成兩張txt   
            for (int i = 0; i < row; i++)
            {
                if (i >= 2) {
                    if (!string.IsNullOrEmpty(dt.Rows[i][0].ToString()))
                    {
                        //總公司QuotaSQl.txt
                        string QuotaSQl = "INSERT INTO dbo.TB_HR_SatisfactionEvaluation_Quota(IId,EvaluationYear , EvaluationType , LocationName ,DescVal ,DeptName ,EvaluationDesc ,enable ,createby ,CreateTime ,updateby ,updateTime)VALUES (" + dt.Rows[i][4].ToString() + ",'2018', '" + dt.Rows[i][0].ToString() + "','" + dt.Rows[i][0].ToString() + "', '" + dt.Rows[i][2].ToString() + "','" + dt.Rows[i][1].ToString() + "','" + dt.Rows[i][3].ToString().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "") + "', 1,'',GETDATE(),'' ,GETDATE());";
                        WriteLog(QuotaSQl, "總公司QuotaSQl", fileNameWithoutExtension);
                    }
                    
                    if (!string.IsNullOrEmpty(dt.Rows[i][4].ToString()))
                    {
                        for (int j = 5; j < col; j++)
                        {
                            if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
                            {
                                //總公司UserSQl.txt
                                string UserSQl = "INSERT INTO dbo.TB_HR_SatisfactionEvaluation_Quota_User( EvaluationYear ,QuotaID ,QuotoDept ,Quoter ,enable ,createby , CreateTime ,updateby ,updateTime ,Dept)VALUES ('2018','" + dt.Rows[i][4].ToString() + "','" + dt.Rows[0][j].ToString() + "','" + dt.Rows[i][j].ToString() + "',1,'sa',GETDATE(),'',GETDATE(),'');";
                                WriteLog(UserSQl, "總公司UserSQl", fileNameWithoutExtension);
                            }
                        }
                    }
                }
            }
            
            MessageBox.Show("讀取信息完畢,已導出txt文件;路徑爲"+ fileNameWithoutExtension + "", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

  

4)關鍵方法excel

public static DataTable GetCsvToDataTable(string strConn, string excelName, string FillName, string rowValue, string ColumnValue)
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn);
            conn.Open();
            DataSet ds = new DataSet();
            System.Data.OleDb.OleDbDataAdapter odda = new System.Data.OleDb.OleDbDataAdapter(string.Format("select * from [" + excelName + "$"+ rowValue + ":"+ ColumnValue + "]"), conn);  //這裏的表名參數,就是 CSV的完整文件名
            odda.Fill(ds, FillName);
            conn.Close();
            return ds.Tables[0];
        }

  

5)寫入txtcode

/// <summary>
        /// 寫入日誌
        /// </summary>
        /// <param name="logstr">寫入的內容</param>
        public static void WriteLog(string logstr,string Txtname,string fileNameWithoutExtension)
        {
            string strFileName = fileNameWithoutExtension+"/"+Txtname+ ".txt";
            using (FileStream fs = new FileStream(strFileName, FileMode.Append))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                {
                    //聲明數據流文件寫入方法  
                    sw.WriteLine(logstr);
                    sw.Close();
                    fs.Close();
                }
            }
        }
相關文章
相關標籤/搜索