通过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;
}
}
/// 导出到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;
}
}
相关文章推荐
- 利用OleDb方式对DataSet 和 Excel 数据快速导入导出
- 导出EXCEL【Web方式HTML通过拼接html中table】
- c#通过OleDb方式读取Excel的最佳做法,不会丢数据
- 通过DataTable导出Excel
- 通过Response输出方式导出Excel
- 通过Response输出方式导出Excel
- Asscess 通过DataTable写入数据到Excel现有模板 ,流文件导出
- 导出Excel文件,npoi方式和通过microsoft.visual basic.dll
- .net 通过NPOI或MyXls把DataTable导出到Excel
- 将datatable导出为excel的三种方式(转)
- Excel导入导出,通过datatable转存(篇一)
- C# 将内存中的datatable数据导出为Excel(方法一,以文件流方式导出)
- 将DataTable导出Excel的三种方式
- ASP.NET通过流方式导出EXCEL并且单元格换行
- 通过OleDB连接方式,访问Access,Excel数据库.
- Repeater 导出excel&数字以文本形式导出到excel&&DataTable通过gridview导出excel
- 将DataTable导出Excel的三种方式
- 利用OleDb方式对DataSet 和 Excel 数据快速导入导出
- DataTable导出Excel的三种方式
- C#导出EXCEL超大数据源码,解决内存溢出问题,使用OLEDB方式(NPOI做不到)