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;
            }
        }


猜你喜欢

转载自blog.csdn.net/douzizuibang/article/details/38655595