How to import data from DataTable to Excel file and create tables by asp.net
This article mainly introduces asp.net how to import data from DataTable to Excel file and create a table. It is very detailed and has a certain reference value. Interested friends must read it!
The details are as follows:
/ Import data from DataTable into Excel file / data source / absolute path of Excel file / the column name / Excel in the corresponding column name / TBL returned True successfully, and failed to return Falsepublic 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) {/ / build table 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) {/ / Import data foreach (DataRow row in dataTable.Rows) {strSQL = "insert into" + dataTable.TableName + "("; for (k = 0; k < TblColName.Length; kits +) {strSQL + = ColumnName [k] + ",";} strSQL = strSQL.Substring (0, strSQL.Length-1); strSQL + = ") values ("; for (k = 0; k < TblColName.Length) Exception ex +) {strSQL + = "'" + row [TblColName] + ",";} 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;}
Call method:
DataSet ds = (DataSet) Session ["listMobile"]; / / get the value if (ds.Tables [0] .Rows.Count) of the table to be exported