C# Excel 导入导出操作类
Code
1 public class ExcelUtil : IDisposable
2 {
3 //是否已经释放资源的标记
4
5 private bool disposed = false;
6
7 private Excel.Application m_objExcel = null;
8 private Excel.Workbooks m_objBooks = null;
9 private Excel._Workbook m_objBook = null;
10 private Excel.Sheets m_objSheets = null;
11 private Excel._Worksheet m_objSheet = null;
12 private Excel.Range m_objRange = null;
13 private DateTime ExcelTime = new DateTime();
14 private int ExcelID = 0;
15 private object m_objOpt = System.Reflection.Missing.Value;
16
17
18
19 /**//// <summary>
20 /// 打开没有模板的操作。
21
22
23 /// </summary>
24 public void Open()
25 {
26 this.Open(String.Empty);
27 }
28
29 /**//// <summary>
30 /// 功能:实现Excel应用程序的打开
31 /// </summary>
32 /// <param name="TemplateFilePath">模板文件物理路径</param>
33 public void Open(string TemplateFilePath)
34 {
35 //打开对象
36 m_objExcel = new Excel.Application();
37
38
39 m_objExcel.Visible = false;
40 m_objExcel.DisplayAlerts = false;
41
42
43
44 m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
45 if (TemplateFilePath.Equals(String.Empty))
46 {
47 m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
48 }
49 else
50 {
51
52 if (File.Exists(TemplateFilePath))
53 {
54 m_objBook = m_objBooks.Open(TemplateFilePath, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
55 m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
56 }
57 else
58 {
59 //Add a new workbook to the file
60 m_objBook = m_objExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
61 }
62
63
64 }
65 m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
66 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
67 }
70
71 private void m_objExcel_WorkbookBeforeClose(Excel.Workbook m_objBooks, ref bool _Cancel)
72 {
73 //MessageBox.Show("保存完毕!");
74 }
75
76
77
78
79
80
81
82
83
84
85 /**//// <summary>
86 /// 给单元格赋值
87
88
89 /// </summary>
90 /// <param name="BeginRangeName"></param>
91 /// <param name="EndRangeName"></param>
92 /// <param name="value"></param>
93 public void SetCellsValue(string BeginRangeName, string EndRangeName, string value)
94 {
95 try
96 {
97 Excel.Range excelCell = (Excel.Range)m_objSheet.get_Range(BeginRangeName, EndRangeName);
98
99 excelCell.Value2 = value;
100
101 }
102 catch (Exception e)
103 {
104
105 throw e;
106 }
107 }
108
109
110
111 /**//// <summary>
112 /// 将Excel文件保存到指定的目录,目录必须事先存在,文件名称不一定要存在。
113
114
115 /// </summary>
116 /// <param name="OutputFilePath">要保存成的文件的全路径。</param>
117 public void SaveFile(string OutputFilePath)
118 {
119 m_objExcel.UserControl = false;
120
121 m_objBook.SaveAs(OutputFilePath, m_objOpt, m_objOpt,
122 m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
123 m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
124
125
126 }
127
128 private void killExcel()
129 {
130 try
131 {
132 Process[] ps = Process.GetProcesses();
133
134
135 foreach (Process p in ps)
136 {
137 if (p.ProcessName.ToLower().Equals("excel"))
138 {
139
140 if (p.Id == ExcelID)
141 {
142 p.Kill();
143 }
144 }
145 }
146 }
147 catch (Exception ex)
148 {
149 //MessageBox.Show("ERROR " + ex.Message);
150 }
151 }
152
153 /**//// <summary>
154 /// 关闭应用程序
155 /// </summary>
156 public void Close()
157 {
158 //m_objBook.Close(false, m_objOpt, m_objOpt);
159 //m_objExcel.Quit();
160
161 try
162 {
163 Dispose();
164 }
165 catch (Exception e)
166 {
167
168 throw e;
169 }
170 }
171
172 /**//// <summary>
173 /// 释放所引用的COM对象。注意:这个过程一定要执行。
174
175
176 /// </summary>
177 public void Dispose()
178 {
179 try
180 {
181 Dispose(true);
182
183 //告诉垃圾回收器,资源已经被回收
184
185
186 GC.SuppressFinalize(this);
187
188 //ReleaseObj(m_objSheets);
189 //ReleaseObj(m_objBook);
190 //ReleaseObj(m_objBooks);
191 //ReleaseObj(m_objExcel);
192 //System.GC.Collect();
193 //System.GC.WaitForPendingFinalizers();
194
195 //Dispose(false);
196 }
197 catch (Exception e)
198 {
199
200 throw e;
201 }
202 }
203
204 /**//// <summary>
205 /// 释放资源
206 /// </summary>
207 /// <param name="disposing"></param>
208 protected virtual void Dispose(bool disposing)
209 {
210 try
211 {
212 if (!disposed)
213 {
214 if (disposing)
215 {
216
217
218 //托管资源的释放
219 //m_objBooks.Close();
220 if (m_objOpt != null && m_objOpt != null)
221 {
222 m_objBook.Close(false, m_objOpt, m_objOpt);
223 }
224
225 //m_objExcel.ActiveWorkbook.Close();
226
227 if (m_objRange != null && m_objSheet != null && m_objSheets != null && m_objBook != null && m_objBooks != null && m_objExcel != null)
228 {
229 ReleaseObj(m_objRange);
230 ReleaseObj(m_objSheet);
231 ReleaseObj(m_objSheets);
232 ReleaseObj(m_objBook);
233 ReleaseObj(m_objBooks);
234 m_objExcel.Quit();
235 ReleaseObj(m_objExcel);
236 }
237
238
239 m_objRange = null;
240 m_objSheet = null;
241 m_objSheets = null;
242 m_objBook = null;
243 m_objBooks = null;
244
245 int generation = GC.GetGeneration(m_objExcel);
246 System.GC.Collect(generation);
247
248 }
249 //非托管资源的释放
250 //killExcel();
251 }
252
253 disposed = true;
254
255
256
257 }
258 catch (Exception e)
259 {
260
261 throw e;
262 }
263 }
264
265 /**//// <summary>
266 /// 析构函数
267 /// </summary>
268 ~ExcelUtil()
269 {
270 try
271 {
272 Dispose(false);
273 }
274 catch (Exception e)
275 {
276
277 throw e;
278 }
279
280 }
281
282 /**//// <summary>
283 /// 释放对象,内部调用
284
285
286 /// </summary>
287 /// <param name="o"></param>
288 private void ReleaseObj(object o)
289 {
290 try
291 {
292 System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
293 }
294 catch { }
295 finally { o = m_objOpt; }
296 }
297
298 /**//// <summary>
299 /// 删除指定sheet下的指定行
300
301
302 /// </summary>
303 /// <param name="SheetIndex">sheet索引</param>
304 /// <param name="DeleteRowIndex">行索引</param>
305 public void DeleteRow(int SheetIndex, int DeleteRowIndex)
306 {
307 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
308 m_objRange = (Excel.Range)m_objSheet.Rows[DeleteRowIndex, System.Reflection.Missing.Value];
309 m_objRange.EntireRow.Delete(Excel.XlDirection.xlToRight);
310 }
311
312 /**//// <summary>
313 /// 删除指定sheet下的指定列
314
315
316 /// </summary>
317 /// <param name="SheetIndex">sheet索引</param>
318 /// <param name="DeleteColumnIndex">列索引</param>
319 public void DeleteColumn(int SheetIndex, int DeleteColumnIndex)
320 {
321 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
322 m_objRange = (Excel.Range)m_objSheet.Columns[DeleteColumnIndex, System.Reflection.Missing.Value];
323 m_objRange.EntireColumn.Delete(Excel.XlDirection.xlDown);
324 }
325
326
327 /**//// <summary>
328 /// DataTable导入excel
329 /// </summary>
330 /// <param name="dt">DataTable</param>
331 /// <param name="Vx">横坐标</param>
332 /// <param name="Vy">纵坐标</param>
333 /// <param name="isuprightness">是否竖排</param>
334 public void ConvertDateTableToExcel(System.Data.DataTable dt, int Vx, int Vy, bool isuprightness)
335 {
336
337 try
338 {
339 //竖排
340 if (isuprightness)
341 {
342 for (int i = 0; i < dt.Rows.Count; i++)
343 {
344 for (int j = 0; j < dt.Columns.Count; j++)
345 {
346 m_objRange = (Excel.Range)m_objSheet.Cells[j + Vy, i + Vx];
347
348 if (i == 0)
349 {
350 //ApplyStyle();
351 }
352
353 m_objRange.Value2 = dt.Rows[i][j].ToString();
354
355 }
356
357 }
358 }
359 else
360 {
361 for (int i = 0; i < dt.Rows.Count; i++)
362 {
363 for (int j = 0; j < dt.Columns.Count; j++)
364 {
365 m_objRange = (Excel.Range)m_objSheet.Cells[i + Vx, j + Vy];
366
367 if (i == 0)
368 {
369 //ApplyStyle();
370 }
371
372 m_objRange.Value2 = dt.Rows[i][j].ToString();
373
374 }
375
376 }
377 }
378 }
379 catch (Exception e)
380 {
381
382 throw e;
383 }
384
385
386
387 }
388
389
390 /**//// <summary>
391 /// 设置列宽
392 /// </summary>
393 /// <param name="columnIndex">列序号</param>
394 public void SetColumnsWidth(int columnIndex, int width)
395 {
396 try
397 {
398 m_objRange = (Excel.Range)m_objSheet.Cells[columnIndex, Type.Missing];
399 m_objRange.ColumnWidth = width;
400
401 }
402 catch (Exception e)
403 {
404
405 throw e;
406 }
407
408 }
409
410
411 /**//// <summary>
412 /// 加密
413 /// </summary>
414 /// <param name="passWord">密码</param>
415 public void SetPassWord(string passWord)
416 {
417 try
418 {
419 m_objBook.Password = passWord;
420 }
421 catch (Exception e)
422 {
423
424 throw e;
425 }
426
427 }
428
429
430
431 /**//// <summary>
432 /// 拷贝指定行到指定行
433
434 /// </summary>
435 /// <param name="SheetIndex"></param>
436 /// <param name="CopyRowIndex">拷贝行号</param>
437 /// <param name="InsertRowIndex">要插入行号</param>
438 public void InsertRow(int SheetIndex, int CopyRowIndex, int InsertRowIndex)
439 {
440 try
441 {
442 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
443 m_objRange = (Excel.Range)m_objSheet.Rows[CopyRowIndex, System.Reflection.Missing.Value];
444 Excel.Range inserRange = (Excel.Range)m_objSheet.Rows[InsertRowIndex, System.Reflection.Missing.Value];
445 inserRange.Insert(Type.Missing, m_objRange.Copy(Type.Missing));
446 }
447 catch (Exception e)
448 {
449
450 throw e;
451 }
452
453
454 }
455
456
457 /**//// <summary>
458 /// 设置光标位置
459 /// </summary>
460 /// <param name="passWord">密码</param>
461 public void Excel_Select(int x, int y)
462 {
463 try
464 {
465 m_objRange = (Excel.Range)m_objSheet.Cells[x, y];
466 m_objRange.Select();
467 }
468 catch (Exception e)
469 {
470
471 throw e;
472 }
473
474 }
475
476
477
478
479
480
481 }
在网上找的源码的基础上修改,在此感谢原创者(忘了原创者是谁)
1 public class ExcelUtil : IDisposable
2 {
3 //是否已经释放资源的标记
4
5 private bool disposed = false;
6
7 private Excel.Application m_objExcel = null;
8 private Excel.Workbooks m_objBooks = null;
9 private Excel._Workbook m_objBook = null;
10 private Excel.Sheets m_objSheets = null;
11 private Excel._Worksheet m_objSheet = null;
12 private Excel.Range m_objRange = null;
13 private DateTime ExcelTime = new DateTime();
14 private int ExcelID = 0;
15 private object m_objOpt = System.Reflection.Missing.Value;
16
17
18
19 /**//// <summary>
20 /// 打开没有模板的操作。
21
22
23 /// </summary>
24 public void Open()
25 {
26 this.Open(String.Empty);
27 }
28
29 /**//// <summary>
30 /// 功能:实现Excel应用程序的打开
31 /// </summary>
32 /// <param name="TemplateFilePath">模板文件物理路径</param>
33 public void Open(string TemplateFilePath)
34 {
35 //打开对象
36 m_objExcel = new Excel.Application();
37
38
39 m_objExcel.Visible = false;
40 m_objExcel.DisplayAlerts = false;
41
42
43
44 m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
45 if (TemplateFilePath.Equals(String.Empty))
46 {
47 m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
48 }
49 else
50 {
51
52 if (File.Exists(TemplateFilePath))
53 {
54 m_objBook = m_objBooks.Open(TemplateFilePath, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
55 m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
56 }
57 else
58 {
59 //Add a new workbook to the file
60 m_objBook = m_objExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
61 }
62
63
64 }
65 m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
66 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
67 }
70
71 private void m_objExcel_WorkbookBeforeClose(Excel.Workbook m_objBooks, ref bool _Cancel)
72 {
73 //MessageBox.Show("保存完毕!");
74 }
75
76
77
78
79
80
81
82
83
84
85 /**//// <summary>
86 /// 给单元格赋值
87
88
89 /// </summary>
90 /// <param name="BeginRangeName"></param>
91 /// <param name="EndRangeName"></param>
92 /// <param name="value"></param>
93 public void SetCellsValue(string BeginRangeName, string EndRangeName, string value)
94 {
95 try
96 {
97 Excel.Range excelCell = (Excel.Range)m_objSheet.get_Range(BeginRangeName, EndRangeName);
98
99 excelCell.Value2 = value;
100
101 }
102 catch (Exception e)
103 {
104
105 throw e;
106 }
107 }
108
109
110
111 /**//// <summary>
112 /// 将Excel文件保存到指定的目录,目录必须事先存在,文件名称不一定要存在。
113
114
115 /// </summary>
116 /// <param name="OutputFilePath">要保存成的文件的全路径。</param>
117 public void SaveFile(string OutputFilePath)
118 {
119 m_objExcel.UserControl = false;
120
121 m_objBook.SaveAs(OutputFilePath, m_objOpt, m_objOpt,
122 m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
123 m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
124
125
126 }
127
128 private void killExcel()
129 {
130 try
131 {
132 Process[] ps = Process.GetProcesses();
133
134
135 foreach (Process p in ps)
136 {
137 if (p.ProcessName.ToLower().Equals("excel"))
138 {
139
140 if (p.Id == ExcelID)
141 {
142 p.Kill();
143 }
144 }
145 }
146 }
147 catch (Exception ex)
148 {
149 //MessageBox.Show("ERROR " + ex.Message);
150 }
151 }
152
153 /**//// <summary>
154 /// 关闭应用程序
155 /// </summary>
156 public void Close()
157 {
158 //m_objBook.Close(false, m_objOpt, m_objOpt);
159 //m_objExcel.Quit();
160
161 try
162 {
163 Dispose();
164 }
165 catch (Exception e)
166 {
167
168 throw e;
169 }
170 }
171
172 /**//// <summary>
173 /// 释放所引用的COM对象。注意:这个过程一定要执行。
174
175
176 /// </summary>
177 public void Dispose()
178 {
179 try
180 {
181 Dispose(true);
182
183 //告诉垃圾回收器,资源已经被回收
184
185
186 GC.SuppressFinalize(this);
187
188 //ReleaseObj(m_objSheets);
189 //ReleaseObj(m_objBook);
190 //ReleaseObj(m_objBooks);
191 //ReleaseObj(m_objExcel);
192 //System.GC.Collect();
193 //System.GC.WaitForPendingFinalizers();
194
195 //Dispose(false);
196 }
197 catch (Exception e)
198 {
199
200 throw e;
201 }
202 }
203
204 /**//// <summary>
205 /// 释放资源
206 /// </summary>
207 /// <param name="disposing"></param>
208 protected virtual void Dispose(bool disposing)
209 {
210 try
211 {
212 if (!disposed)
213 {
214 if (disposing)
215 {
216
217
218 //托管资源的释放
219 //m_objBooks.Close();
220 if (m_objOpt != null && m_objOpt != null)
221 {
222 m_objBook.Close(false, m_objOpt, m_objOpt);
223 }
224
225 //m_objExcel.ActiveWorkbook.Close();
226
227 if (m_objRange != null && m_objSheet != null && m_objSheets != null && m_objBook != null && m_objBooks != null && m_objExcel != null)
228 {
229 ReleaseObj(m_objRange);
230 ReleaseObj(m_objSheet);
231 ReleaseObj(m_objSheets);
232 ReleaseObj(m_objBook);
233 ReleaseObj(m_objBooks);
234 m_objExcel.Quit();
235 ReleaseObj(m_objExcel);
236 }
237
238
239 m_objRange = null;
240 m_objSheet = null;
241 m_objSheets = null;
242 m_objBook = null;
243 m_objBooks = null;
244
245 int generation = GC.GetGeneration(m_objExcel);
246 System.GC.Collect(generation);
247
248 }
249 //非托管资源的释放
250 //killExcel();
251 }
252
253 disposed = true;
254
255
256
257 }
258 catch (Exception e)
259 {
260
261 throw e;
262 }
263 }
264
265 /**//// <summary>
266 /// 析构函数
267 /// </summary>
268 ~ExcelUtil()
269 {
270 try
271 {
272 Dispose(false);
273 }
274 catch (Exception e)
275 {
276
277 throw e;
278 }
279
280 }
281
282 /**//// <summary>
283 /// 释放对象,内部调用
284
285
286 /// </summary>
287 /// <param name="o"></param>
288 private void ReleaseObj(object o)
289 {
290 try
291 {
292 System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
293 }
294 catch { }
295 finally { o = m_objOpt; }
296 }
297
298 /**//// <summary>
299 /// 删除指定sheet下的指定行
300
301
302 /// </summary>
303 /// <param name="SheetIndex">sheet索引</param>
304 /// <param name="DeleteRowIndex">行索引</param>
305 public void DeleteRow(int SheetIndex, int DeleteRowIndex)
306 {
307 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
308 m_objRange = (Excel.Range)m_objSheet.Rows[DeleteRowIndex, System.Reflection.Missing.Value];
309 m_objRange.EntireRow.Delete(Excel.XlDirection.xlToRight);
310 }
311
312 /**//// <summary>
313 /// 删除指定sheet下的指定列
314
315
316 /// </summary>
317 /// <param name="SheetIndex">sheet索引</param>
318 /// <param name="DeleteColumnIndex">列索引</param>
319 public void DeleteColumn(int SheetIndex, int DeleteColumnIndex)
320 {
321 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
322 m_objRange = (Excel.Range)m_objSheet.Columns[DeleteColumnIndex, System.Reflection.Missing.Value];
323 m_objRange.EntireColumn.Delete(Excel.XlDirection.xlDown);
324 }
325
326
327 /**//// <summary>
328 /// DataTable导入excel
329 /// </summary>
330 /// <param name="dt">DataTable</param>
331 /// <param name="Vx">横坐标</param>
332 /// <param name="Vy">纵坐标</param>
333 /// <param name="isuprightness">是否竖排</param>
334 public void ConvertDateTableToExcel(System.Data.DataTable dt, int Vx, int Vy, bool isuprightness)
335 {
336
337 try
338 {
339 //竖排
340 if (isuprightness)
341 {
342 for (int i = 0; i < dt.Rows.Count; i++)
343 {
344 for (int j = 0; j < dt.Columns.Count; j++)
345 {
346 m_objRange = (Excel.Range)m_objSheet.Cells[j + Vy, i + Vx];
347
348 if (i == 0)
349 {
350 //ApplyStyle();
351 }
352
353 m_objRange.Value2 = dt.Rows[i][j].ToString();
354
355 }
356
357 }
358 }
359 else
360 {
361 for (int i = 0; i < dt.Rows.Count; i++)
362 {
363 for (int j = 0; j < dt.Columns.Count; j++)
364 {
365 m_objRange = (Excel.Range)m_objSheet.Cells[i + Vx, j + Vy];
366
367 if (i == 0)
368 {
369 //ApplyStyle();
370 }
371
372 m_objRange.Value2 = dt.Rows[i][j].ToString();
373
374 }
375
376 }
377 }
378 }
379 catch (Exception e)
380 {
381
382 throw e;
383 }
384
385
386
387 }
388
389
390 /**//// <summary>
391 /// 设置列宽
392 /// </summary>
393 /// <param name="columnIndex">列序号</param>
394 public void SetColumnsWidth(int columnIndex, int width)
395 {
396 try
397 {
398 m_objRange = (Excel.Range)m_objSheet.Cells[columnIndex, Type.Missing];
399 m_objRange.ColumnWidth = width;
400
401 }
402 catch (Exception e)
403 {
404
405 throw e;
406 }
407
408 }
409
410
411 /**//// <summary>
412 /// 加密
413 /// </summary>
414 /// <param name="passWord">密码</param>
415 public void SetPassWord(string passWord)
416 {
417 try
418 {
419 m_objBook.Password = passWord;
420 }
421 catch (Exception e)
422 {
423
424 throw e;
425 }
426
427 }
428
429
430
431 /**//// <summary>
432 /// 拷贝指定行到指定行
433
434 /// </summary>
435 /// <param name="SheetIndex"></param>
436 /// <param name="CopyRowIndex">拷贝行号</param>
437 /// <param name="InsertRowIndex">要插入行号</param>
438 public void InsertRow(int SheetIndex, int CopyRowIndex, int InsertRowIndex)
439 {
440 try
441 {
442 m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
443 m_objRange = (Excel.Range)m_objSheet.Rows[CopyRowIndex, System.Reflection.Missing.Value];
444 Excel.Range inserRange = (Excel.Range)m_objSheet.Rows[InsertRowIndex, System.Reflection.Missing.Value];
445 inserRange.Insert(Type.Missing, m_objRange.Copy(Type.Missing));
446 }
447 catch (Exception e)
448 {
449
450 throw e;
451 }
452
453
454 }
455
456
457 /**//// <summary>
458 /// 设置光标位置
459 /// </summary>
460 /// <param name="passWord">密码</param>
461 public void Excel_Select(int x, int y)
462 {
463 try
464 {
465 m_objRange = (Excel.Range)m_objSheet.Cells[x, y];
466 m_objRange.Select();
467 }
468 catch (Exception e)
469 {
470
471 throw e;
472 }
473
474 }
475
476
477
478
479
480
481 }
幽夜底衣角,那一片清风。