標籤:datagridview style blog color io os 使用 ar for
一 . 使用Excel物件模型建立Excel文檔:
1.建立簡單的文檔
1 try 2 { 3 //建立Excel程式對象 4 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 5 //設定建立WorkBook時,WorkBook包含表單個數 6 excel.SheetsInNewWorkbook = 1; 7 //建立WorkBook 8 excel.Workbooks.Add(); 9 10 //建立第一個工作表11 Worksheet sheet = excel.ActiveWorkbook.Sheets[1];12 //Worksheet sheet = (Worksheet)excel.ActiveWorkbook.Worksheets[1];13 14 //給工作表設定名稱15 sheet.Name = "Student";16 sheet.Cells[1, 1] = txtName.Text;17 sheet.Cells[1, 2] = txtAge.Text;18 sheet.Cells[1, 3] = txtHabit.Text;19 20 //顯示Excel21 excel.Visible = true;22 //現場休眠2000毫秒23 System.Threading.Thread.Sleep(2000);24 25 //儲存當前活動的WorkBook26 excel.ActiveWorkbook.SaveAs(27 //Environment.CurrentDirectory + "/test.xls",//檔案名稱28 "f:/test.xls",29 XlFileFormat.xlWorkbookNormal //儲存檔案的格式30 );31 32 //關閉當前活動的WorkBook33 excel.ActiveWorkbook.Close();34 //退出Excel應用程式35 excel.Quit();36 }37 catch (Exception ex)38 {39 40 throw new Exception(ex.Message);41 }
2.設定文檔格式
1 //設定字型樣式 2 Range ranRow = sheet.Range[sheet.Cells[2, 2], sheet.Cells[2, 10]]; 3 ranRow.Font.Bold = true;//字型加粗 4 ranRow.Font.Color = Color.SeaGreen;//字型顏色 5 //儲存格操作 6 ranRow.HorizontalAlignment=XlHAlign.xlHAlignCenter;//對齊 7 ranRow .Interior.Color = Color.SeaGreen;//內邊框樣式 8 range.MergeCells = true;//合併儲存格 9 //邊框樣式:10 ranBorder.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick);//地區外邊框樣式11 range.Borders.LineStyle = XlLineStyle.xlDouble;//內邊框樣式 12 //設定社會安全號碼碼,日期顯示格式13 range.NumberFormat = "0";14 range.NumberFormatLocal = "yyyy-m-d";
二. 使用物件模型匯出DataGridView資料到Excel文檔
1.直接在表單設計介面代碼使用DataGridView作為資料來源,直接使用顯示出來的值填充Excel表格。
2.將DataGridView作為參數,傳遞到公用類中,需要在公用類中添加並匯入 using System.Windows.Forms;
三. 匯入Excel文檔到DataTable中
1 //建立Datatable對象,並添加列 2 System.Data.DataTable dt = new System.Data.DataTable(); 3 for (int i = 0; i < 10; i++) 4 { 5 dt.Columns.Add(new DataColumn()); 6 } 7 8 Worksheet sheet = null; 9 foreach (Worksheet sh in excel.ActiveWorkbook.Worksheets)10 {11 if (sh.Name == "Sheet1")12 {13 sheet = sh;14 }15 if (sheet != null)16 {17 int r = 2;18 while (true)19 {20 Range rName = sheet.Cells[r, 3] as Range;21 if (rName.Text.ToString().Trim().Length == 0)22 {23 break;24 }25 DataRow row = dt.NewRow();26 27 28 for (int i = 0; i < 10; i++)29 {30 row[i] = sheet.Cells[r, i + 1].Text;31 32 }33 dt.Rows.Add(row);34 r++;35 }36 }37 }
四. 使用ADO.NET匯入Excel內容
1 //連接字串 2 string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=‘E:/N-Tier/Lesson8/學生基本資料.xls‘;Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1‘"; 3 string sql = string.Format("select * from [{0}$]", "Sheet1"); 4 DataTable dt = new DataTable(); 5 using (OleDbConnection con = new OleDbConnection(conStr)) 6 { 7 con.Open(); 8 OleDbDataAdapter odda = new OleDbDataAdapter(sql, con); 9 odda.Fill(dt);10 }11 return dt;
Asp.net中操作Excel的代碼解析