using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Data.OleDb; using Excel; using System.Reflection; using System.Runtime.InteropServices;// For COMException public partial class readandwrite_excel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ReadExcel(); Response.Write("下面是寫入XLS文件"); WriteXls(); WriteAndAutoSaveXls(); } /**//// <summary> /// 讀取一個XLSW文件並顯示出來 /// </summary> public void ReadExcel() { string oleconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\\WebCHat\\excel\\test.xls;Extended Properties='Excel 8.0;HDR=NO'"; // HDR=NO 即無字段 // HDR=yes 即有字段,一般默認excel表中第1行的列標題為字段名,如姓名、年齡等 //如果您在連接字符串中指定 HDR=NO,Jet OLE DB 提供程序將自動為您命名字段(F1 表示第一個字段,F2 表示第二個字段,依此類推); // IMEX 表示是否強制轉換為文本 // Excel 驅動程序讀取指定源中一定數量的行(默認情況下為 8 行)以推測每列的數據類型。 //如果推測出列可能包含混合數據類型(尤其是混合了文本數據的數值數據時), //驅動程序將決定采用占多數的數據類型,並對包含其他類型數據的單元返回空值。 //(如果各種數據類型的數量相當,則采用數值類型。) //Excel 工作表中大部分單元格格式設置選項不會影響此數據類型判斷。 //可以通過指定導入模式來修改 Excel 驅動程序的此行為。 //若要指定導入模式,請在“屬性”窗口中將 IMEX=1 添加到 Excel //連接管理器的連接字符串內的擴展屬性值中。 OleDbConnection conn = new OleDbConnection(oleconn); conn.Open(); string str_sql = "select * from [Sheet1$]"; OleDbDataAdapter oda = new OleDbDataAdapter(str_sql, conn); DataSet ds = new DataSet(); oda.Fill(ds); conn.Close(); GridView1.DataSource = ds; GridView1.DataBind(); } /**//// <summary> /// 將一些數據寫入到一個XLS文件中 /// </summary> public void WriteXls() { Excel.Application excel = new Excel.Application(); excel.Workbooks.Add(true); excel.Cells[1, 1] = "1,1"; excel.Cells[1, 2] = "1,2"; excel.Cells[1, 3] = "1,3"; excel.Cells[2, 1] = "2,1"; excel.Cells[2, 2] = "2,2"; excel.Cells[2, 3] = "2,3"; excel.Visible = true; } /**//// <summary> /// 實現自動保存 /// </summary> ///參考 http://hi.baidu.com/happybadbaby/blog/item/c396ae231ef5f4549822ed58.html public void WriteAndAutoSaveXls() { Excel.Application excel = new Excel.Application(); Range range = null;// 創建一個空的單元格對象 Worksheet sheet = null; try { // 注釋掉的語句是:從磁盤指定位置打開一個 Excel 文件 //excel.Workbooks.Open("demo.xls", Missing.Value, Missing.Value, //Missing.Value,Missing.Value, Missing.Value, Missing.Value, //Missing.Value, Missing.Value, Missing.Value, Missing.Value, //Missing.Value, Missing.Value, Missing.Value, Missing.Value); if(excel==null) { Response.Write("不能創建excle文件"); } excel.Visible = false;// 不顯示 Excel 文件,如果為 true 則顯示 Excel 文件 excel.Workbooks.Add(Missing.Value);// 添加工作簿 //使用 Missing 類的此實例來表示缺少的值,例如,當您調用具有默認參數值的方法時。 sheet = (Worksheet)excel.ActiveSheet;// 獲取當前工作表 sheet.get_Range(sheet.Cells[29,2],sheet.Cells[29,2]).Orientation=Excel.XlOrientation.xlVertical;//字體豎直居中在單元格內 range = sheet.get_Range("A1", Missing.Value);// 獲取單個單元格 range.RowHeight = 20; // 設置行高 range.ColumnWidth = 20; // 設置列寬 range.Borders.LineStyle = 1; // 設置單元格邊框 range.Font.Bold = true; // 加粗字體 range.Font.Size = 20; // 設置字體大小 range.Font.ColorIndex = 5; // 設置字體顏色 range.Interior.ColorIndex = 6; // 設置單元格背景色 range.HorizontalAlignment = XlHAlign.xlHAlignCenter;// 設置單元格水平居中 range.VerticalAlignment = XlVAlign.xlVAlignCenter;// 設置單元格垂直居中 range.Value2 = "設置行高和列寬";// 設置單元格的值 range = sheet.get_Range("B2", "D4");// 獲取多個單元格 range.Merge(Missing.Value); // 合並單元格 range.Columns.AutoFit(); // 設置列寬為自動適應 range.NumberFormatLocal = "#,##0.00";// 設置單元格格式為貨幣格式 // 設置單元格左邊框加粗 range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick; // 設置單元格右邊框加粗 range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick; range.Value2 = "合並單元格"; // 頁面設置 sheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4; // 設置頁面大小為A4 sheet.PageSetup.Orientation = XlPageOrientation.xlPortrait; // 設置垂直版面 sheet.PageSetup.HeaderMargin = 0.0; // 設置頁眉邊距 sheet.PageSetup.FooterMargin = 0.0; // 設置頁腳邊距 sheet.PageSetup.LeftMargin = excel.InchesToPoints(0.354330708661417); // 設置左邊距 sheet.PageSetup.RightMargin = excel.InchesToPoints(0.354330708661417);// 設置右邊距 sheet.PageSetup.TopMargin = excel.InchesToPoints(0.393700787401575); // 設置上邊距 sheet.PageSetup.BottomMargin = excel.InchesToPoints(0.393700787401575);// 設置下邊距 sheet.PageSetup.CenterHorizontally = true; // 設置水平居中 // 打印文件 sheet.PrintOut(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); // 保存文件到程序運行目錄下 sheet.SaveAs("e:\\WebChat\\excel\\demo.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); excel.ActiveWorkbook.Close(false, null, null); // 關閉 Excel 文件且不保存 } catch (Exception ex) { Response.Write(ex.Message); } finally { excel.Quit(); // 退出 Excel System.Runtime.InteropServices.Marshal.ReleaseComObject(range); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); GC.Collect(); } } }