C# Excel 相关导入导出操作

最近一段时间,由于工作需要,需要做数据库与Excel 的导入导出,由于以前没接触过,有点难煞我也。

迎难直上,查证N多资料,终于做出最稳定,最方便的解决方案,封装为类,方便自己以后使用查看,附代码。

个人认为比较适合基础较差的开发同志,涉及的知识点很少,属于一看就懂的那种,你懂的。

废话少说,看代码:

excel导入到sql server 数据库:

View Code
  1 using System;
  2 using System.Data;
  3 using System.Data.SqlClient;
  4 using TongLu.DatasInfo.DataLayer;
  5 using Sql = TongLu.PMethod.Sql;
  6 using SqlProc = TongLu.SqlProc;
  7 using System.Data.OleDb;
  8 using System.Collections; 
  9 
 10 namespace TongLu.DatasInfo.DataLayer.DBHelper
 11 {
 12     public class ExcelOperation
 13     {
 14         /// <summary>
 15         /// 加载Excel
 16         /// </summary>
 17         /// <param name="filePath">本地完整路径</param>
 18         /// <param name="tableName">Excel中表名(Sheet1)</param>
 19         /// <returns>返回DataSet</returns>
 20         public static DataSet LoadDataFromExcel(string filePath, string tableName)
 21         {
 22             try
 23             {
 24                 if (!tableName.EndsWith("$"))
 25                 {
 26                     tableName = tableName+"$";
 27                 }
 28 
 29                 string strConn = string.Empty;
 30                 if (filePath.Substring(filePath.LastIndexOf('.')).Equals(".xls"))
 31                 {
 32                     strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
 33                 }
 34                 else
 35                 {
 36                     strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
 37                 }
 38                 OleDbConnection OleConn = new OleDbConnection(strConn);
 39                 OleConn.Open();
 40                 string sql = "SELECT * FROM [" + tableName + "]";//[Sheet1$]";//可更改Sheet名称,比如sheet2,等等
 41 
 42                 OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
 43                 DataSet ds = new DataSet();
 44                 OleDaExcel.Fill(ds, tableName);
 45                 OleConn.Close();
 46                 return ds;
 47             }
 48             catch
 49             {
 50                 return null;
 51             }
 52         }
 53         /// <summary>
 54         /// 服务器安全设置阻止此操作OpenDataSource
 55         /// </summary>
 56         /// <param name="filePath"></param>
 57         /// <param name="tableName"></param>
 58         /// <returns></returns>
 59         public static int InsertDataListIntoSql(string filePath, string tableName)
 60         {
 61             string connstr = "SELECT * into Chain_cashphone_card FROM OpenDataSource('Microsoft.Jet.OLEDB.4.0','Data Source="
 62                 +"\""+filePath+"\";User ID=administrator;Password=;Extended properties=Excel 8.0')..."+tableName;
 63             SqlCommand cmd = new SqlCommand(connstr);
 64             int res = 0;
 65                 res= (int)(new Sql.SqlConn().sqlExecObj(cmd));
 66             return res;
 67 
 68         }
 69 
 70 
 71         /// <summary>   
 72         /// 数据集操作   
 73         /// </summary>   
 74         /// <param name="ds"></param>   
 75         public static  string DataSetOperator(DataSet ds)  
 76         {  
 77             SqlConnection conn = new SqlConnection(new Sql.SqlConn().getStringConnention());  
 78             conn.Open();
 79             string Mess = string.Empty;
 80             SqlTransaction str = conn.BeginTransaction();//利用事务处理 防止中断   
 81             int k = 0;
 82             int Datacount = 0;
 83             for (int n = 0; n < ds.Tables.Count; n++)
 84             {
 85                 if (ds.Tables[n].Rows.Count < 1)
 86                 {
 87                     Mess = "没有数据!";
 88                     Datacount++;
 89                 }
 90                 if (ds.Tables.Count == Datacount)
 91                 {
 92                     return Mess;
 93                 }
 94 
 95             }
 96             try  
 97             {
 98                 for (int j = 0; j < ds.Tables.Count; j++)
 99                 {
100                     for (int i = 0; i < ds.Tables[j].Rows.Count; i++)
101                     {
102                         string sqlStr = "insert into chain_CashPhone_Card(CardNO,CardPwd,ExpireTime,ServiceName,CardName,PurPrice,Price,Cost,Block,IsUsed,AddTime,IsValid,ProductCode,Area)values";
103                         sqlStr += "('" + ds.Tables[j].Rows[i][0].ToString() + "','";
104                         sqlStr += ds.Tables[j].Rows[i][1].ToString() + "','";
105                         sqlStr += ds.Tables[j].Rows[i][2].ToString() + "','";
106                         sqlStr += ds.Tables[j].Rows[i][3].ToString() + "','";
107                         sqlStr += ds.Tables[j].Rows[i][4].ToString() + "',";
108                         sqlStr += ds.Tables[j].Rows[i][5].ToString() + ",";
109                         sqlStr += ds.Tables[j].Rows[i][6].ToString() + ",";
110                         sqlStr += ds.Tables[j].Rows[i][7].ToString() + ",'',";
111                         sqlStr += ds.Tables[j].Rows[i][8].ToString() + ",getDate(),";
112                         sqlStr += ds.Tables[j].Rows[i][9].ToString() + ",'','";
113                         sqlStr += ds.Tables[j].Rows[i][10].ToString() + "')";
114                         SqlCommand cmd = new SqlCommand(sqlStr, conn, str);
115                         cmd.Transaction = str;
116                         k += cmd.ExecuteNonQuery();
117                     }
118                 }
119                 str.Commit();  
120             }  
121             catch (Exception ex)  
122             {  
123                 Mess="发生异常,数据已回滚/n信息/n" + ex.Message;  
124                 str.Rollback();
125                 return Mess;
126             }  
127             finally  
128             {  
129                 Mess="上传成功" + k + "";
130             }
131             return Mess;
132         }  
133 
134 
135 
136         /// <summary>
137         /// 将ds中表插入数据库表中
138         /// </summary>
139         /// <param name="ds">DataSet</param>
140         /// <param name="tableName">数据库中表名</param>
141         /// <returns>返回状态</returns>
142         public static string ExcelToSql(DataSet ds, string tableName)
143         {
144             try
145             {
146                 if (ds != null && ds.Tables.Count>0)
147                 {
148                     string conn = TongLu.DatasInfo.SqlHelper.ConnectionStringLocalTransaction;
149                     SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.UseInternalTransaction);
150                     sqlbulkcopy.DestinationTableName = tableName;//数据库中的表名
151                     for (int i = 0; i < ds.Tables.Count; i++)
152                     {
153                         sqlbulkcopy.WriteToServer(ds.Tables[i]);
154                     }
155                 }
156                 else
157                 {
158                     return "数据加载失败,文件路径错误!";
159                 }
160             }
161             catch(Exception e)
162             {
163                 return e.Message;//"导入异常,请确认表数据是否规范或有重复添加!";
164             }
165             return "导入成功!";
166         }
167 
168         public static ArrayList GetExcelSheetNameList(string filePath)
169         {
170             string strConn = string.Empty;
171             if (filePath.Substring(filePath.LastIndexOf('.')).Equals(".xls"))
172             {
173                 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
174             }
175             else
176             {
177                 strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
178             }
179             OleDbConnection Conn = new OleDbConnection(strConn);
180             Conn.Open();
181 
182             //在传递限制数组的值时,对于不包含值的数组元素使用 Visual C# .NET 的 null 关键字。例如,如果要检索表的架构,使用 OleDbSchemaGuid.Tables。
183             //DataTable 中返回的每一列是限制列(TABLE_CATALOG、TABLE_SCHEMA、TABLE_NAME、TABLE_TYPE),后面是 TABLE_GUID、DESCRIPTION、TABLE_PROPID、DATE_CREATED 和 DATE_MODIFIED 的其他架构列。
184             //object[] 数组中的[3]="TABLE" 对应 TABLE_TYPE,TABLE_NAME对应 [2]
185             DataTable dtSheetNameList = Conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null,null,null,"TABLE"});
186             Conn.Close();
187 
188             ArrayList ai = new ArrayList();
189             foreach (DataRow dr in dtSheetNameList.Rows)
190             {
191                 ai.Add(dr[2].ToString());//或 ai.Add(dr.ItemArray[2].ToString());
192             }
193             return ai;
194         }
195 
196     }
197 }
复制代码

相信以上大家都可以看得懂,此类方法可兼容office07下(包涵07)版本,个别知识点,大家可以自己去查证,在下就不多说了。导入数据的时候,个别数据需要处理的,比如excel空行数据要剔除,excel自动把比较长的数据科学计数法转换,

这里就需要在导入的时候稍作处理了,方法应该很多,每人都有不同理解,就不献丑了,鄙人的比较粗糙,欢迎有简便处理的可以贴出来讨论讨论,本人的代码就不贴了,个人认为不太科学,不误导大家了。。

看下面,导出数据库查询数据到excel

这个地方要稍微注意的就是中文乱码问题,主要是编码方式,大家要谨慎对待,个人测试发现utf-7目前较好,大家可以测试测试,当然网上也有一些其他的解决方法,大家可以自己看看,有更好的方式了,欢迎大家贴出来,分享下,知识无国界嘛,还有就是输出方式了。

代码:

根据本人测试,该导出封装类,操作比较稳定,基本不会出现导出表出现不能查看的问题,方法考虑了大部分情况,基础是一样的,使用需要各位去筛选。就不赘述了。强调一点,该保存的excel最好使用office的打开,向wps之类的,统计函数是office标准,可能不太好使。
转载请注明,谢谢。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,您可以使用以下代码实现 DataGridView 数据的导入导出 Excel 文件的功能。 导入 Excel 文件到 DataGridView: ```csharp using System; using System.Data; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; public void ImportExcelToDataGridView(DataGridView dataGridView, string filePath) { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(filePath); Excel.Worksheet worksheet = workbook.ActiveSheet; int rowCount = worksheet.UsedRange.Rows.Count; int columnCount = worksheet.UsedRange.Columns.Count; DataTable dataTable = new DataTable(); for (int col = 1; col <= columnCount; col++) { dataTable.Columns.Add(worksheet.Cells[1, col].Value.ToString()); } for (int row = 2; row <= rowCount; row++) { DataRow dataRow = dataTable.NewRow(); for (int col = 1; col <= columnCount; col++) { dataRow[col - 1] = worksheet.Cells[row, col].Value; } dataTable.Rows.Add(dataRow); } dataGridView.DataSource = dataTable; workbook.Close(); excelApp.Quit(); } ``` 导出 DataGridView 数据到 Excel 文件: ```csharp using System; using System.Data; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; public void ExportDataGridViewToExcel(DataGridView dataGridView, string filePath) { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Add(); Excel.Worksheet worksheet = workbook.ActiveSheet; for (int col = 1; col <= dataGridView.Columns.Count; col++) { worksheet.Cells[1, col] = dataGridView.Columns[col - 1].HeaderText; worksheet.Cells[1, col].Font.Bold = true; } for (int row = 0; row < dataGridView.Rows.Count; row++) { for (int col = 0; col < dataGridView.Columns.Count; col++) { worksheet.Cells[row + 2, col + 1] = dataGridView.Rows[row].Cells[col].Value.ToString(); } } worksheet.Columns.AutoFit(); workbook.SaveAs(filePath); workbook.Close(); excelApp.Quit(); } ``` 您可以调用 `ImportExcelToDataGridView` 方法将 Excel 文件导入到 DataGridView,传入要导入的 DataGridView 对象和 Excel 文件路径。调用 `ExportDataGridViewToExcel` 方法将 DataGridView 数据导出Excel 文件,传入要导出的 DataGridView 对象和 Excel 文件路径。 请注意,导入导出 Excel 文件需要在项目中引用 Microsoft.Office.Interop.Excel 库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值