C#操作Excel_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C#操作Excel

C#操作Excel

 2013/8/6 13:08:39  37℃守望  博客园  我要评论(0)
  • 摘要:1.读取excel中的内容stringpath=Server.MapPath("/ExcelUpload/data_limited.xls");stringsConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+path+";"+"ExtendedProperties=Excel8.0;";//建立EXCEL的连接OleDbConnectionobjConn=newOleDbConnection
  • 标签:C# excel 操作

1.读取excel中的内容

           string path = Server.MapPath("/ExcelUpload/data_limited.xls");
            string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + path + ";" +
                "Extended Properties=Excel 8.0;";

            //建立EXCEL的连接
            OleDbConnection objConn = new OleDbConnection(sConnectionString);

            objConn.Open();
            OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet5$]", objConn);
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
            objAdapter1.SelectCommand = objCmdSelect;

            DataSet objDataset1 = new DataSet();

            objAdapter1.Fill(objDataset1, "XLData");
            System.Data.DataTable dtExcel = objDataset1.Tables[0];

            objConn.Close();

2.创建excel表格

         GC.Collect();
            Application excel;
            int colIndex = 1;
            int rowIndex = 1;
            _Workbook xBk;
            _Worksheet xSt;
            excel = new Application();
            xBk = excel.Workbooks.Add(true);
            xSt = (_Worksheet)xBk.ActiveSheet;

            循环写单元格内容

             excel.Cells[rowIndex, num + 1] = dr[num];
            xSt.Range[excel.Cells[rowIndex, num + 1], excel.Cells[rowIndex, num + 1]].HorizontalAlignment = XlVAlign.xlVAlignCenter;

            string xlsFile = @"d:\ErrorComment.xls";
            xSt.SaveAs(xlsFile);

            自动打开文件夹

            Process.Start("Explorer", "/select," + xlsFile);

发表评论
用户名: 匿名