using System;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Web;
namespace Common
{
public class ExcelHelper
{
protected static LogHelper Logger = new LogHelper("ExcelHelper");
public static void ExportExcel(DataTable data, string fileName)
{
try
{
if (data != null && data.Rows.Count > 0)
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Charset = "Utf-8";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls", Encoding.UTF8));
StringBuilder sbHtml = new StringBuilder();
sbHtml.AppendLine("");
sbHtml.AppendLine("
");
sbHtml.AppendLine("");
foreach (DataColumn column in data.Columns)
{
sbHtml.AppendLine("" + column.ColumnName + " | ");
}
sbHtml.AppendLine("
");
foreach (DataRow row in data.Rows)
{
sbHtml.Append("");
foreach (DataColumn column in data.Columns)
{
sbHtml.Append("").Append(row[column].ToString()).Append(" | ");
}
sbHtml.AppendLine("
");
}
sbHtml.AppendLine("
");
HttpContext.Current.Response.Write(sbHtml.ToString());
HttpContext.Current.Response.End();
}
}
catch (Exception ex)
{
ExcelHelper.Logger.WriteLog("-----------Excel导出数据异常-----------\r\n" + ex.ToString() + "\r\n");
}
}
private static string ConnectionString(string fileName)
{
return string.Format(fileName.EndsWith(".xls") ? "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;" : "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES\"", fileName);
}
public static DataTable ExcelToDataSet(string sheet, string filename)
{
DataTable result;
try
{
OleDbConnection myConn = new OleDbConnection(ExcelHelper.ConnectionString(filename));
string strCom = " SELECT * FROM [" + sheet + "$]";
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
DataSet ds = new DataSet();
myCommand.Fill(ds);
myConn.Close();
result = ds.Tables[0];
}
catch (Exception ex)
{
ExcelHelper.Logger.WriteLog("-----------Excel导入数据异常-----------\r\n" + ex.ToString() + "\r\n");
result = null;
}
return result;
}
}
}