EXCEL的导入导出

  1 using System;
  2 using System.Data;
  3 using System.Data.OleDb;
  4 using System.IO;
  5 
  6 namespace COMMON
  7 {
  8     public class Excel_OutputInput
  9     {
 10         private int _ReturnStatus;
 11         private string _ReturnMessage;
 12 
 13         /// <summary>
 14         /// 执行返回状态
 15         /// </summary>
 16         public int ReturnStatus
 17         {
 18             get
 19             {
 20                 return _ReturnStatus;
 21             }
 22         }
 23 
 24         /// <summary>
 25         /// 执行返回信息
 26         /// </summary>
 27         public string ReturnMessage
 28         {
 29             get
 30             {
 31                 return _ReturnMessage;
 32             }
 33         }
 34 
 35         public Excel_OutputInput()
 36         {
 37         }
 38 
 39 
 40         /// <summary>
 41         /// 导入EXCEL到DataSet
 42         /// </summary>
 43         /// <param name="fileName">Excel全路径文件名</param>
 44         /// <returns>导入成功的DataSet</returns>
 45         public DataTable ImportExcel(string fileName)
 46         {
 47             //判断是否安装EXCEL
 48             Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
 49             if (xlApp == null)
 50             {
 51                 _ReturnStatus = -1;
 52                 _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
 53                 return null;
 54             }
 55 
 56             //判断文件是否被其他进程使用            
 57             Microsoft.Office.Interop.Excel.Workbook workbook;
 58             try
 59             {
 60                 workbook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
 61             }
 62             catch
 63             {
 64                 _ReturnStatus = -1;
 65                 _ReturnMessage = "Excel文件处于打开状态,请保存关闭";
 66                 return null;
 67             }
 68 
 69             //获得所有Sheet名称
 70             int n = workbook.Worksheets.Count;
 71             string[] SheetSet = new string[n];
 72             System.Collections.ArrayList al = new System.Collections.ArrayList();
 73             for (int i = 1; i <= n; i++)
 74             {
 75                 SheetSet[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i]).Name;                
 76             }
 77 
 78             //释放Excel相关对象
 79             workbook.Close(null, null, null);
 80             xlApp.Quit();
 81             if (workbook != null)
 82             {
 83                 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
 84                 workbook = null;
 85             }
 86             if (xlApp != null)
 87             {
 88                 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
 89                 xlApp = null;
 90             }
 91             GC.Collect();
 92 
 93             //把EXCEL导入到DataSet
 94             DataSet ds = new DataSet();
 95             DataTable table = new DataTable();
 96             string conStr;
 97             FileInfo file = new FileInfo(fileName);
 98             string extention = file.Extension;
 99             switch (extention)
100             {
101                 case ".xls":
102                     conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0";
103                     break;
104                 case ".xlsx":
105                     conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0";
106                     break;
107                 default:
108                     conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0";
109                     break;
110             }
111 
112             //string connStr = " Provider = Microsoft.Jet.OLEDB.12.0 ; Data Source = " + fileName + ";Extended Properties=Excel 12.0";
113             using (OleDbConnection conn = new OleDbConnection(conStr))
114             {
115                 conn.Open();
116                 OleDbDataAdapter da;
117                 string sql = "select * from [" + SheetSet[0] + "$] ";
118                 da = new OleDbDataAdapter(sql, conn);
119                 da.Fill(ds, SheetSet[0]);
120                 da.Dispose();
121                 table = ds.Tables[0];
122                 conn.Close();
123                 conn.Dispose();
124             }
125             return table;
126         }
127 
128         /// <summary>
129         /// 把DataTable导出到EXCEL
130         /// </summary>
131         /// <param name="reportName">报表名称</param>
132         /// <param name="dt">数据源表</param>
133         /// <param name="saveFileName">Excel全路径文件名</param>
134         /// <returns>导出是否成功</returns>
135         public bool ExportExcel(string reportName, System.Data.DataTable dt, string saveFileName)
136         {
137             if (dt == null)
138             {
139                 _ReturnStatus = -1;
140                 _ReturnMessage = "数据集为空!";
141                 return false;
142             }
143 
144             bool fileSaved = false;
145             Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
146             if (xlApp == null)
147             {
148                 _ReturnStatus = -1;
149                 _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
150                 return false;
151             }
152 
153             Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
154             Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
155             Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
156             worksheet.Cells.Font.Size = 10;
157             Microsoft.Office.Interop.Excel.Range range;
158 
159             long totalCount = dt.Rows.Count;
160             long rowRead = 0;
161             float percent = 0;
162 
163             worksheet.Cells[1, 1] = reportName;
164             ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, 1]).Font.Size = 12;
165             ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, 1]).Font.Bold = true;
166 
167             //写入字段
168             for (int i = 0; i < dt.Columns.Count; i++)
169             {
170                 worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
171                 range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[2, i + 1];
172                 range.Interior.ColorIndex = 15;
173                 range.Font.Bold = true;
174 
175             }
176             //写入数值
177             for (int r = 0; r < dt.Rows.Count; r++)
178             {
179                 for (int i = 0; i < dt.Columns.Count; i++)
180                 {
181                     worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i].ToString();
182                 }
183                 rowRead++;
184                 percent = ((float)(100 * rowRead)) / totalCount;
185             }            
186             range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]];
187             range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
188             if (dt.Rows.Count > 0)
189             {
190                 range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
191                 range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
192                 range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
193             }
194             if (dt.Columns.Count > 1)
195             {
196                 range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
197                 range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
198                 range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
199             }
200 
201             //保存文件
202             if (saveFileName != "")
203             {
204                 try
205                 {
206                     workbook.Saved = true;
207                     workbook.SaveCopyAs(saveFileName);
208                     fileSaved = true;
209                 }
210                 catch (Exception ex)
211                 {
212                     fileSaved = false;
213                     _ReturnStatus = -1;
214                     _ReturnMessage = "导出文件时出错,文件可能正被打开!
" + ex.Message;
215                 }
216             }
217             else
218             {
219                 fileSaved = false;
220             }
221 
222             //释放Excel对应的对象
223             if (range != null)
224             {
225                 System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
226                 range = null;
227             }
228             if (worksheet != null)
229             {
230                 System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
231                 worksheet = null;
232             }
233             if (workbook != null)
234             {
235                 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
236                 workbook = null;
237             }
238             if (workbooks != null)
239             {
240                 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
241                 workbooks = null;
242             }
243             xlApp.Application.Workbooks.Close();
244             xlApp.Quit();
245             if (xlApp != null)
246             {
247                 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
248                 xlApp = null;
249             }
250             GC.Collect();
251             return fileSaved;
252         }
253     }
254 }
原文地址:https://www.cnblogs.com/Sunflower-/p/5531020.html