1. 程式人生 > >c#操作wps中的excel

c#操作wps中的excel

在c#中可以操作office的excel,這個是比較簡單,直接引入類庫操作。操作wps中的excel比其比較麻煩。

第一步:首先將wps的相關COM元件新增至引用. 工程->新增引用->COM->Kingsoft ET 2.0 Object Library / Upgrade Kinsoft ET 3.0 Object Library

第二步:Using KSO;Using ET;(匯入Kingsoft ET 2.0 Object Library時引用)

              Using EXCEL;(匯入Upgrade Kinsoft ET 3.0 Object Library時引用)

第三步:將資料儲存在c#記憶體中定義的資料表中。

 static void Dataprocessing(String tagid,String actionid)
        {
            System.Data.DataTable dt = new System.Data.DataTable();  //定義資料表變數
            //資料庫中執行查詢的SQL語句
            string sql = string.Format("SELECT * from RSSIData where ActionId='"+actionid+"'");
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            SqlCommand cmd = new SqlCommand(sql, connection);
            SqlDataReader reader = cmd.ExecuteReader();
            //生成表格的每列的標題(以我的程式為例)
            for (int i = 0; i < 7; i++)
            {
                if (i == 0){dt.Columns.Add("讀寫器ID", typeof(string)); }
                else if(i==1) { dt.Columns.Add("標籤ID", typeof(string)); }
                else if (i == 2) { dt.Columns.Add("標籤負載", typeof(string)); }
                else if (i == 3) { dt.Columns.Add("A通道RSSI值", typeof(string)); }
                else if (i == 4) { dt.Columns.Add("B通道RSSI值", typeof(string)); }
                else if (i == 5) { dt.Columns.Add("測試時間", typeof(string)); }
                else if (i == 6) { dt.Columns.Add("資料標識ID", typeof(string)); }
            }
            //根據資料庫查詢的結果,一一將資料填寫在對應的dt行中
            while(reader.Read())
            {
              DataRow dr = dt.NewRow();
              for (int j = 0; j <7; j++)//for迴圈一次,生成一行資料
              {
                  if (j == 0){ dr[j] = reader["ReaderId"]; }
                  else if(j==1){ dr[j] = reader["TagId"];}
                  else if (j == 2) { dr[j] = reader["Payload"]; }
                  else if (j == 3) { dr[j] = reader["RSSI"]; }
                  else if (j == 4) { dr[j] = reader["RSSIB"]; }
                  else if (j == 5) { dr[j] = reader["CollectTime"]; }
                  else if (j == 6) { dr[j] = reader["ActionId"]; }
              }
              dt.Rows.Add(dr); 
            }
            string s = OutputWPSExcel(dt, "第二組小方格測試的四個標籤資料報表", "C:\\users\\acer\\Desktop\\導師的\\定位資料統計\\");
             Console.Write(s); 
        }

第四步:將dt中的資料儲存在wps的excel中
/// 
        /// 將DataTable的資料匯出顯示為報表(使用WPS)
        /// 
        /// 要匯出的資料
        /// 匯出報表的標題
        /// 儲存檔案的路徑
        /// 
        static string OutputWPSExcel(System.Data.DataTable dt, string strTitle, string FilePath)
        {
            DateTime beforeTime = DateTime.Now;
            object missing = Type.Missing;
            Excel.Range objRange = null;
            string filename = "";
            try
            {
                objApp = new Excel.Application();

                objWorkBook = objApp.Workbooks.Add(Type.Missing);
                objWorkSheet = objWorkBook.ActiveSheet;
                int rowIndex = 4;
                int colIndex = 1;
                //取得列標題	
                foreach (DataColumn col in dt.Columns)
                {
                    colIndex++;
                    excel.Cells[4, colIndex]
                    objWorkSheet.Cells[4,colIndex] =  col.ColumnName;
                    //設定標題格式為居中對齊

                    Range range = objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(4, colIndex),(object) objWorkSheet.Cells.get_Item(4, colIndex));
                    range.Font.Bold = true;
                    range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    range.Select();
                }
                 //取得表格中的資料	
                foreach (DataRow row in dt.Rows)
                {
                    rowIndex++;
                    colIndex = 1;
                    foreach (DataColumn col in dt.Columns)
                    {
                        colIndex++;
                        if (col.DataType == System.Type.GetType("System.DateTime"))
                        {
                            objWorkSheet.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
                            objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(rowIndex, colIndex));//設定日期型的欄位格式為居中對齊
                        }
                        else
                            if (col.DataType == System.Type.GetType("System.String"))
                            {
                                Range txtRange = (Range)objWorkSheet.Cells[rowIndex, colIndex];
                                txtRange.NumberFormatLocal = "@";
                                objWorkSheet.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(rowIndex, colIndex),(object) objWorkSheet.Cells.get_Item(rowIndex, colIndex)).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//設定字元型的欄位格式為居中對齊
                            }
                            else
                            {
                                objWorkSheet.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                            }
                    }
                }
                //載入一個合計行	
                int rowSum = rowIndex + 1;
                int colSum = 2;
                objWorkSheet.Cells[rowSum, 2] = "合計";
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(rowSum, 2), (object)objWorkSheet.Cells.get_Item(rowSum, 2)).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                //取得整個報表的標題	
                objWorkSheet.Cells[2, 2] = strTitle;
                //設定整個報表的標題格式	
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(2, 2), (object)objWorkSheet.Cells.get_Item(2, 2)).Font.Bold = true;
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(2, 2), (object)objWorkSheet.Cells.get_Item(2, 2)).Font.Size = 22;

                //設定報表表格為最適應寬度	
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(4, 2), (object)objWorkSheet.Cells.get_Item(rowSum, colIndex)).Select();
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(4, 2), (object)objWorkSheet.Cells.get_Item(rowSum, colIndex)).Columns.AutoFit();

                //設定整個報表的標題為跨列居中	
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(2, 2), (object)objWorkSheet.Cells.get_Item(2, colIndex)).Select();
                objWorkSheet.get_Range((object)objWorkSheet.Cells.get_Item(2, 2), (object)objWorkSheet.Cells.get_Item(2, colIndex)).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection;

                DateTime afterTime = DateTime.Now;
                filename =FilePath+ strTitle + "_" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
                //儲存檔案
                objWorkBook.SaveAs(filename, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing);
                objWorkBook.Close(missing, missing, missing);
            }
            finally
            {
                ReleaseComObject(objRange);
                ReleaseComObject(objWorkSheet);
                ReleaseComObject(objWorkBook);
            }
            return filename;
        }
        static void ReleaseComObject(object obj)
        {
            if (obj != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
        }