一 . 使用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 //显示Excel 21 excel.Visible = true; 22 //现场休眠2000毫秒 23 System.Threading.Thread.Sleep(2000); 24 25 //保存当前活动的WorkBook 26 excel.ActiveWorkbook.SaveAs( 27 //Environment.CurrentDirectory + "/test.xls",//文件名 28 "f:/test.xls", 29 XlFileFormat.xlWorkbookNormal //保存文件的格式 30 ); 31 32 //关闭当前活动的WorkBook 33 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;