Excel + SQL Server 导入导出类
来源:互联网 发布:?+?=123风靡网络 编辑:程序博客网 时间:2024/05/01 17:42
using System.Data;using System.Data.OleDb;using System.Data.SqlClient;using System.Collections.Generic;using System.Web.UI.WebControls;using System;using System.Linq;using System.Web;namespace CableDB.Web.admin.Experiment.DB{ public class ExcelHelper { #region 将DataTable 写入数据库 /// <summary> /// 事物插入到数据库中 /// </summary> /// <param name="sqlConn">数据库连接字符串</param> /// <param name="dt">保存数据的DataTable</param> /// <param name="tableName">目标数据表的表名</param> /// <returns></returns> public static bool DataTableToDB(string sqlConn, DataTable dt, string tableName, ) { using (SqlConnection conn = new SqlConnection(sqlConn)) { if (conn.State == ConnectionState.Closed) { conn.Open(); } using (SqlBulkCopy sqlCopy = new SqlBulkCopy(conn)) { sqlCopy.DestinationTableName = tableName; sqlCopy.BulkCopyTimeout = 180; try { sqlCopy.WriteToServer(dt); } catch (System.Exception ex) { return false; } finally { conn.Close(); } } } return true; } #endregion #region /// <summary> /// 从Excel读入数据到DataSet /// </summary> /// <param name="strFilePath">Excel文件路径</param> /// <returns>返回Excel转化为的DataSet</returns> public static DataSet ExcelToDataSet(string strFilePath) { string strConn = ""; if (System.IO.Path.GetExtension(strFilePath).Equals(".xls")) { strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'"; } else if (System.IO.Path.GetExtension(strFilePath).Equals(".xlsx")) { strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + strFilePath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'"; } else { return null; } OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });//获得Excel中的所有sheetname OleDbDataAdapter odda; DataSet ds = new DataSet(); foreach (DataRow dr in sheetNames.Rows) { DataSet dsOne = new DataSet(); odda = new OleDbDataAdapter("select * from [" + dr[2] + "]", strConn);//dr[2] is sheetname odda.Fill(dsOne); if (dsOne.Tables.Count > 0) { DataTable dt = dsOne.Tables[0].Copy(); dt.TableName = dr[2].ToString(); ds.Tables.Add(dt); } } conn.Close(); return ds; } #endregion #region 将 DataSet 导入 Excel /// <summary> /// This method takes DataSet as input paramenter and it exports the same to excel /// </summary> /// <param name="ds"></param> public static void DataSetToExcel(DataSet ds, string strFileName) { //Creae an Excel application instance Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); //Create an Excel workbook instance and open it from the predefined location Microsoft.Office.Interop.Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(System.Reflection.Missing.Value); foreach (DataTable table in ds.Tables) { //Add a new worksheet to workbook with the Datatable name Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add(); excelWorkSheet.Name = table.TableName; for (int i = 1; i < table.Columns.Count + 1; i++) { excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName; } for (int j = 0; j < table.Rows.Count; j++) { for (int k = 0; k < table.Columns.Count; k++) { excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString(); } } } excelWorkBook.SaveAs(strFileName); excelWorkBook.Close(); excelApp.Quit(); } #endregion /// <summary> /// 执行SQL语句,将结果保存至DataSet中,然后返回。 /// </summary> /// <param name="strConn">数据库连接字符串</param> /// <param name="strSQL">SQL语句</param> /// <returns>SQL执行结果</returns> public static DataSet DBToDataSet(string strConn, string strSQL) { using (SqlConnection conn = new SqlConnection(strConn)) { DataSet ds = new DataSet(); try { if (conn.State == ConnectionState.Closed) conn.Open(); SqlCommand cmd = new SqlCommand(strSQL, conn); using (SqlDataAdapter adpter = new SqlDataAdapter(cmd)) { adpter.Fill(ds); } } catch (Exception exp) { CableDB.Common.Log.OutputError(exp.ToString()); } return ds; } } /// <summary> /// 客户端下载Excel文件,同时删除服务器上的文件。 /// </summary> /// <param name="Response"></param> /// <param name="strFileName">Excel文件路径</param> public static void DownloadExcel(HttpResponse Response, string strFileName) { //打开要下载的文件,并把该文件存放在FileStream中 System.IO.FileStream Reader = System.IO.File.OpenRead(strFileName); //文件传送的剩余字节数:初始值为文件的总大小 long Length = Reader.Length; Response.Buffer = false; Response.AddHeader("Connection", "Keep-Alive"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"); Response.AddHeader("Content-Length", Length.ToString()); byte[] Buffer = new Byte[10000]; //存放欲发送数据的缓冲区 int ByteToRead; //每次实际读取的字节数 while (Length > 0) { //剩余字节数不为零,继续传送 if (Response.IsClientConnected) { //客户端浏览器还打开着,继续传送 ByteToRead = Reader.Read(Buffer, 0, 10000); //往缓冲区读入数据 Response.OutputStream.Write(Buffer, 0, ByteToRead); //把缓冲区的数据写入客户端浏览器 Response.Flush(); //立即写入客户端 Length -= ByteToRead; //剩余字节数减少 } else { //客户端浏览器已经断开,阻止继续循环 Length = -1; } } //关闭该文件 Reader.Close(); if (System.IO.File.Exists(strFileName)) System.IO.File.Delete(strFileName); } }}
0 0
- Excel + SQL Server 导入导出类
- Sql Server导入导出Excel
- Sql Server 导入导出Excel
- 使用SQL Server导入/导出Excel
- 从sql server中导入/导出 excel
- SQL Server导入导出excel
- excel数据导入导出SQL Server 2005
- SQL Server导入导出excel及常见问题
- EXCEL导入导出SQL
- sql server 导入导出!!
- SQL Server导入导出
- Sql Server 导入导出
- 导入导出sql server
- 从SQL Server中导入/导出 Excel 的基本方法
- 从SQL Server中导入/导出 Excel 的基本方法
- 从SQL Server中导入/导出 Excel 的基本方法
- SQL SERVER 和ACCESS/excel的数据导入导出
- 从SQL Server中导入/导出 Excel 的基本方法
- OC中的协议
- typedef与define的区别
- t-sql写入图片到数据库
- HMM学习笔记_3(从一个实例中学习Viterbi算法)
- bitset
- Excel + SQL Server 导入导出类
- python + fiddler抓包测试
- Robust PCA 学习笔记
- SVN工具的使用 和在Eclipse中安装GPD插件:(多步审批流,因此选择使用工作流(JBPM)来实现)
- Perl之单行命令特技
- ------------------java正则表达式验证邮箱、手机号码
- PHP 基础知识 (一)
- 我怀念的
- 找完全二叉树最底层最右边的结点