1 using System; 2 using System.Data; 3 using System.Data.OleDb; 4 using System.IO; 5 6 namespace DAL 7 { 8 /// <summary> 9 /// Peng制作 10 /// <para>QQ:378781081</para> 11 /// </summary> 12 /// <see cref="http://www.cnblogs.com/VAllen"/> 13 public class ExcelHelper 14 { 15 /// <summary> 16 /// 初始化一個Excel操作實例 17 /// <para>請注意,本連接字符串不支持office2010,如需支持,請自行更改連接字符串格式</para> 18 /// </summary> 19 /// <param name="pathString">請提供一個Excel文件路徑,無論是已創建的或者是未創建的</param> 20 public ExcelHelper(string pathString) 21 { 22 this.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + 23 pathString + 24 ";Extended Properties=Excel 8.0;Persist Security Info=False"; 25 odc = new OleDbConnection(ConnectionString); 26 } 27 28 private readonly string ConnectionString;//連接字符串 29 public OleDbConnection odc;//連接對象 30 31 /// <summary> 32 /// 返回一個Excel文檔中的所有數據 33 /// </summary> 34 /// <param name="sql">SQL語句</param> 35 /// <returns></returns> 36 public DataSet ReadExcel(string sql) 37 { 38 DataSet ds = new DataSet(); 39 odc.Open(); 40 OleDbDataAdapter oda = new OleDbDataAdapter(sql, odc); 41 oda.Fill(ds); 42 odc.Close(); 43 return ds; 44 } 45 46 /// <summary> 47 /// 返回一個Excel文檔中第一個Sheet檔的Sheet數據 48 /// </summary> 49 /// <returns></returns> 50 public DataTable ReadExcel() 51 { 52 odc.Open(); 53 DataTable dt = odc.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, 54 new object[] { null, null, null, "TABLE" }); 55 odc.Close(); 56 return dt; 57 } 58 59 /// <summary> 60 /// 打開一個已存在的Excel文檔,並寫入數據集 61 /// <para>請注意,Excel文檔內的多個Sheet有可能被覆蓋</para> 62 /// <para>原因:Sheet名相同</para> 63 /// </summary> 64 /// <param name="ds">數據集,至少包含一個或多個表(Sheet)</param> 65 /// <param name="pathString">請提供一個Excel文件路徑,如果不存在則自動創建</param> 66 /// <returns></returns> 67 public bool WriteExcel(DataSet ds, string pathString) 68 { 69 if (!File.Exists(pathString)) 70 { 71 FileStream fs = File.Create(pathString); 72 fs.Dispose(); 73 fs.Close(); 74 } 75 bool result = true; 76 Microsoft.Office.Interop.Excel.Application excel = 77 new Microsoft.Office.Interop.Excel.Application();//創建Excel操作對象 78 excel.Workbooks.Open(pathString); 79 try 80 { 81 excel.SheetsInNewWorkbook = ds.Tables.Count;//創建sheet的數量 82 excel.Workbooks.Add();//添加sheet 83 for (int number = 0; number < ds.Tables.Count; number++) 84 { 85 Microsoft.Office.Interop.Excel.Worksheet sheet = 86 excel.ActiveWorkbook.Worksheets[number + 1] as 87 Microsoft.Office.Interop.Excel.Worksheet;//獲取sheet; 88 DataTable dt = ds.Tables[number];//獲取表 89 sheet.Name = dt.TableName;//設置sheet名 90 int i = 0; 91 for (; i < dt.Columns.Count; i++)//動態添加 92 { 93 sheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;//添加表頭 94 } 95 Microsoft.Office.Interop.Excel.Range range = 96 excel.get_Range(excel.Cells[1, 1], excel.Cells[1, i]);//編輯區域 97 range.Font.Bold = true;//字體加粗 98 range.Font.Color = 0;//字體顏色 99 range.Interior.ColorIndex = 15; 100 range.ColumnWidth = 15;//列寬 101 range.Borders.LineStyle = 102 Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;//邊框樣式 103 for (int y = 0; y < dt.Rows.Count; y++)//動態添加行數據 104 { 105 for (int x = 0; x < dt.Rows[y].Table.Columns.Count; x++)//動態添加列數據 106 { 107 sheet.Cells[y + 2, x + 1] = dt.Rows[y][x];//賦值 108 } 109 } 110 } 111 excel.Visible = true;//顯示預覽 112 System.Threading.Thread.Sleep(5000); 113 excel.ActiveWorkbook.Save(); 114 } 115 catch (Exception ex) 116 { 117 ex.Message.ToString(); 118 result = false; 119 } 120 finally 121 { 122 excel.ActiveWorkbook.Close();//關閉Excel對象 123 excel.Quit();//退出 124 } 125 return result; 126 } 127 128 /// <summary> 129 /// 創建一個新的Excel文件,並寫入數據集 130 /// <para>請注意,Excel文件可能創建失敗</para> 131 /// <para>原因:指定Excel文件已存在</para> 132 /// </summary> 133 /// <param name="ds">數據集,至少包含一個或多個表(Sheet)</param> 134 /// <param name="pathString">請提供一個Excel文件路徑,如果不存在則自動創建</param> 135 /// <returns></returns> 136 public bool CreateExcel(DataSet ds, string pathString) 137 { 138 bool result = true; 139 Microsoft.Office.Interop.Excel.Application excel = 140 new Microsoft.Office.Interop.Excel.Application();//create Excel manipulate objects 141 try 142 { 143 excel.SheetsInNewWorkbook = ds.Tables.Count;//獲取Sheet檔數量 144 excel.Workbooks.Add(); 145 for (int number = 0; number < ds.Tables.Count; number++)//循環添加Sheet檔 146 { 147 Microsoft.Office.Interop.Excel.Worksheet sheet = 148 excel.ActiveWorkbook.Worksheets[number + 1] as 149 Microsoft.Office.Interop.Excel.Worksheet;//獲取sheet; 150 DataTable dt = ds.Tables[number];//獲取表 151 sheet.Name = dt.TableName;//設置Sheet檔名 152 int i = 0; 153 for (; i < dt.Columns.Count; i++)//循環添加列頭 154 { 155 sheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;//設置列頭名 156 } 157 Microsoft.Office.Interop.Excel.Range range = 158 excel.get_Range(excel.Cells[1, 1], excel.Cells[1, i]);//設置編輯區域 159 range.Font.Bold = true;//字體加粗 160 range.Font.ColorIndex = 0;//字體顏色 161 range.Interior.ColorIndex = 15;//背景顏色 162 range.ColumnWidth = 15;//列寬 163 range.Borders.LineStyle = 164 Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;//邊框樣式 165 range.HorizontalAlignment = 166 Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//字體居中 167 for (int y = 0; y < dt.Rows.Count; y++)//循環添加行 168 { 169 for (int x = 0; x < dt.Rows[y].Table.Columns.Count; x++)//循環添加列 170 { 171 sheet.Cells[y + 2, x + 1] = dt.Rows[y][x];//設置列值 172 } 173 } 174 } 175 excel.Visible = true;//設置為預覽 176 System.Threading.Thread.Sleep(5000);//線程延遲5秒再預覽 177 excel.ActiveWorkbook.SaveAs(pathString, 178 Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);//另存為 179 } 180 catch (Exception ex) 181 { 182 ex.Message.ToString(); 183 result = false; 184 } 185 finally 186 { 187 excel.ActiveWorkbook.Close();//關閉Excel對象 188 excel.Quit();//退出 189 } 190 return result; 191 } 192 } 193 }
應用示例:
1 using System.Collections.Generic; 2 using System.Data; 3 using Model; 4 5 namespace DAL 6 { 7 public class StudentExcelServices 8 { 9 public StudentExcelServices(string pathString) 10 { 11 this.pathString = pathString; 12 eh = new ExcelHelper(pathString); 13 } 14 15 private ExcelHelper eh; 16 private string pathString; 17 18 //填充一個數據集 19 public void ReadExcel(string sheetName,out DataSet ds) 20 { 21 string sql = string.Format( 22 "select * from [{0}] where [編號] is not null", 23 sheetName); 24 ds = eh.ReadExcel(sql); 25 return ds; 26 } 27 28 //讀取所有學生信息 29 public List<Student> ReadExcel() 30 { 31 List<Student> studentList = new List<Student>(); 32 Microsoft.Office.Interop.Excel.Application excel = 33 new Microsoft.Office.Interop.Excel.Application(); 34 excel.Workbooks.Open(pathString); 35 Microsoft.Office.Interop.Excel.Workbook work = 36 excel.Workbooks[1] as Microsoft.Office.Interop.Excel.Workbook; 37 //省略封裝的代碼 38 return studentList; 39 } 40 41 //打開Excel並且寫入數據判斷是否成功 42 public bool WriteExcel(DataSet ds) 43 { 44 bool result = eh.WriteExcel(ds, pathString); 45 return result; 46 } 47 48 //創建Excel並且寫入數據判斷是否成功 49 public bool CreateExcel(DataSet ds) 50 { 51 bool result = eh.CreateExcel(ds, pathString); 52 return result; 53 } 54 55 //讀取所有班級名稱 56 public List<string> ReadGradeList(string sheetName) 57 { 58 List<string> gradeList = new List<string>(); 59 string sql = string.Format( 60 "select [班級] from [{0}] where [班級] is not null group by [班級]", 61 sheetName); 62 DataSet ds = eh.ReadExcel(sql); 63 foreach (DataTable item in ds.Tables) 64 { 65 foreach (DataRow row in item.Rows) 66 { 67 gradeList.Add(row[0].ToString()); 68 } 69 } 70 return gradeList; 71 } 72 73 //讀取所有Sheet檔名稱 74 public List<string> ReadSheetNameList() 75 { 76 List<string> sheetNameList = new List<string>(); 77 DataTable dt = eh.ReadExcel(); 78 foreach (DataRow item in dt.Rows) 79 { 80 sheetNameList.Add(item["TABLE_NAME"].ToString()); 81 } 82 return sheetNameList; 83 } 84 } 85 } 86 87 //這是實體類 88 using System; 89 90 namespace Model 91 { 92 //學生類 93 [Serializable] 94 public class Student 95 { 96 public int StudentNo { get; set; }//編號/帳號 97 public string LoginPwd { get; set; }//密碼 98 public string StudentName { get; set; }//姓名 99 public string Gender{get;set;}//性別 100 public Grade GradeName { get; set; }//班級 101 public string Phone { get; set; }//聯系電話 102 public string Address { get; set; }//地址 103 public DateTime BornDate { get; set; }//生日 104 public string Email { get; set; }//郵箱 105 public string IdentityCard { get; set; }//身份證號碼 106 } 107 }
轉載的朋友,請不要刪除以下行,對此,表示感謝!!!
原文鏈接:http://www.cnblogs.com/VAllen/articles/ExcelHelper_Peng.html