百度空间 | 百度首页 
 
查看文章
 
读写Excel
2009-04-27 20:25

private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = ReadExcel(@"d:\db.xls");
            DTtoExcel(dt, @"d:\db2.xls");
            return;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sExcelFile"></param>
        /// <returns></returns>
        public System.Data.DataTable ReadExcel(string sExcelFile)
        {
            string sConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + sExcelFile + ";Extended Properties=Excel 8.0";
            OleDbConnection connection = new OleDbConnection(sConnectionString);
            OleDbDataAdapter adp = new OleDbDataAdapter("SELECT * FROM testTable", connection);
            DataSet ds = new DataSet();
            adp.Fill(ds, "Book1");
            return ds.Tables[0];
        }

        private void DTtoExcel(System.Data.DataTable dt, String fname)
        {

            Excel.Application excel = new Excel.Application();

            int rowIndex = 1;
            int colIndex = 0;
            Excel.Workbook xbook = excel.Workbooks.Add(true);

            foreach (DataColumn col in dt.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }

            foreach (DataRow row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach (DataColumn col in dt.Columns)
                {
                    colIndex++;
                    excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                }

            }
            xbook.SaveAs(fname, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            xbook = null;
            excel.Quit();
            excel = null;
        }


类别:Office | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu