您的位置:首页 > 其它

通过oledb方式将DataTable导出到Excel

2012-09-13 12:01 295 查看
/// <summary>

/// 导出到Excel

/// </summary>

/// <param name="ds">数据集</param>

public void DataTableToExcel(DataTable ds)

{

string serverpath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);

///创建xls副本

string fileTemName = "FileName";

string tbl = serverpath + @"JXNum\JXBackManage\JXPhoneStorageVindicate\TempFile\" + fileTemName + ".xls";

int mins = DateTime.Now.Hour * 60 * 60 + DateTime.Now.Minute * 60 + DateTime.Now.Second;

fileTemName = fileTemName + mins.ToString();

#region 创建文件夹

string filepath = @"C:\TEMP"; //文件夹的路径

if (!Directory.Exists(filepath))//如果不存在的话创建

{

try

{

Directory.CreateDirectory(filepath);

}

catch (Exception ex)

{

throw ex;

}

}

string fileName = "FileName.xls";

string fileFullPath = filepath + @"\" + fileName;

FileStream fs = null;

StreamWriter sw = null;

if (File.Exists(fileFullPath))//如果存在该文件的话,删除文件

{

File.Delete(fileFullPath);//删除文件

fs = new FileStream(fileFullPath, FileMode.Append);

sw = new StreamWriter(fs);

sw.Flush();

// sw.WriteLine(sHtml);

sw.Close();

fs.Close();

}

else

{

sw = File.CreateText(fileFullPath);

//sw.WriteLine(sHtml);

sw.Close();

}

string filetemPath = filepath+@"\" + fileTemName + ".xls";

File.Copy(tbl, filetemPath, true);

#endregion 创建文件夹

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();

conn.ConnectionString = UICommBase.GetConnectionString(filetemPath);

conn.Open();

string PathName = UICommBase.GetTableName(conn);

#region 写入

for (int i = 0; i < ds.Rows.Count; i++)

{

System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();

cmd.Connection = conn;

string sql = "insert into [" + PathName + "](列1,列2,列3,列4) ";

sql += "values(" + ds.Rows[i]["列1"].ToString() + ",'" + ds.Rows[i]["列2"].ToString() + "'," + ds.Rows[i]["列3"].ToString() + ",'" + ds.Rows[i]["列4"].ToString() + "')";

cmd.CommandText = sql;

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

}

ds.Clear();

ds.Dispose();

conn.Close();

conn.Dispose();

Response.ContentType = "application/ms-excel";

Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(fileTemName)) + ".xls");

Response.BinaryWrite(File.ReadAllBytes(filetemPath));

Response.Flush();

File.Delete(filetemPath);

Response.Clear();

Response.Close();

#endregion

/// <summary>

/// UICommBase 的摘要说明

/// </summary>

public class UICommBase

{

public UICommBase()

{

//

// TODO: 在此处添加构造函数逻辑

//

}

public static string GetConnectionString(string filePath)

{

return GetConnectionString(filePath, true, null);

}

public static string GetConnectionString(string filePath, bool hasHeader, Nullable<int> imexMode)

{

string propHDR = string.Format("HDR={0};", hasHeader ? "Yes" : "No");

string propIMEX = (imexMode.HasValue ? string.Format("IMEX={0};", imexMode.Value) : string.Empty);

string connString = string.Format(@"Provider=Microsoft.Ace.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;{1}{2}""", filePath, propHDR, propIMEX);

return connString;

}

public static string GetTableName(OleDbConnection conn)

{

string tableName = null;

DataTable dt;

dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

if (dt.Rows.Count >= 1)

{

DataRow dr = dt.Rows[0];

object obj = dr["TABLE_NAME"];

if (obj != null && obj != DBNull.Value)

{

tableName = obj.ToString();

}

}

return string.IsNullOrEmpty(tableName) ? "Sheet1$" : tableName;

}

public static DataTable GetData(OleDbConnection conn, string tableName, string field)

{

string selectText = string.Format("SELECT * FROM [{0}] ", tableName, field);//where [{1}]

OleDbCommand cmd = new OleDbCommand(selectText, conn);

DataTable dt = null;

using (OleDbDataAdapter odda = new OleDbDataAdapter(selectText, conn))

{

dt = new DataTable();

odda.Fill(dt);

}

return dt;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: