这篇文章主要介绍asp.net如何实现数据从DataTable导入到Excel文件并创建表,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
具体如下:
/// <summary> /// 把数据从DataTable导入到Excel文件里 /// </summary> /// <param name="dataTable">数据源</param> /// <param name="AbsoluteExcelFilePath">Excel文件的绝对路径</param> /// <param name="TblColName">TBL里对应的列名</param> /// <param name="ColumnName">Excel中对应的列名</param> /// <returns>操作成功返回True,失败返回False</returns> public static bool ExportDataToExcel(DataTable dataTable, string AbsoluteExcelFilePath, string[] TblColName, string[] ColumnName) { int k = 0; if (dataTable == null) return false; OleDbConnection Conn = new OleDbConnection(); try { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AbsoluteExcelFilePath + ";Mode=Share Deny None;Extended Properties=Excel 8.0;Jet OLEDB:Create System Database=True"; Conn = new OleDbConnection(strConn); Conn.Open(); OleDbCommand command = Conn.CreateCommand(); string strSQL = ""; if (dataTable.Columns != null) { //建表 strSQL = "CREATE TABLE " + dataTable.TableName + "("; for (int i = 0; i < ColumnName.Length; i++) { strSQL += ColumnName[i] + " TEXT,"; } strSQL = strSQL.Substring(0, strSQL.Length - 1); strSQL += ")"; command.CommandText += strSQL; command.ExecuteNonQuery(); if (dataTable.Rows.Count > 0) { //导入数据 foreach (DataRow row in dataTable.Rows) { strSQL = "insert into " + dataTable.TableName + "("; for (k = 0; k < TblColName.Length; k++) { strSQL += ColumnName[k] + ","; } strSQL = strSQL.Substring(0, strSQL.Length - 1); strSQL += ") values( "; for (k = 0; k < TblColName.Length; k++) { strSQL += "'" + row[TblColName[k]] + "',"; } strSQL = strSQL.Substring(0, strSQL.Length - 1); strSQL += ")"; command.CommandText = strSQL; command.ExecuteNonQuery(); } } } } catch (Exception ex) { Conn.Close(); throw new Exception(ex.Message); return false; } Conn.Close(); return true; }
调用方法:
DataSet ds = (DataSet)Session["listMobile"];//获得要导出的表格的值 if (ds.Tables[0].Rows.Count <= 0) { Page.RegisterStartupScript("", "<mce:script type="text/javascript"><!-- alert('没有内容不能导出!') // --></mce:script>"); } else { //EXCEL页面的名称 string[] tableName = { "["+DateTime.Now.ToString("yyyyMMddhhmmss")+"]" }; string fileName = tools.CreateID() + ".xls"; string filePath = Server.MapPath("..//DownloadFiles//" + fileName); if (tools.ExportDataToExcel(ds, filePath, tableName)==true) { Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentType = "application/vnd.ms-excel"; this.EnableViewState = false; Response.WriteFile(filePath); Response.Flush(); if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath); Response.Redirect(this.Request.UrlReferrer.AbsoluteUri, true); Response.End(); } }
以上是“asp.net如何实现数据从DataTable导入到Excel文件并创建表”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。