从DataTable中导出Excel:
public static void ExportToExcelByDataTableAndFileName(DataTable dt, string FileName)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", FileName));
HttpContext.Current.Response.ContentType = "application/vnd.xls";
HttpContext.Current.Response.ContentEncoding = System.Text.UTF8Encoding.Default;
string colHeaders = "", ls_item = "";
DataRow[] myRow = dt.Select();
int i = 0;
int cl = dt.Columns.Count;
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
colHeaders += dt.Columns[i].Caption.ToString() + "\r\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
HttpContext.Current.Response.Write(colHeaders);
//sw.Write(colHeaders);
foreach (DataRow row in myRow)
{
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
ls_item += row[i].ToString() + "\r\n";
}
else
{
ls_item += row[i].ToString() + "\t";
}
}
HttpContext.Current.Response.Write(ls_item);
//sw.Write(ls_item);
ls_item = "";
}
HttpContext.Current.Response.End();
//sw.Close();
//fileStream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
public static void ExportToExcelByDataTableAndFileNameAndColumnName(IList<string> columnNameList, DataTable dt, string FileName)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", FileName));
HttpContext.Current.Response.ContentType = "application/vnd.xls";
HttpContext.Current.Response.ContentEncoding = System.Text.UTF8Encoding.Default;
string colHeaders = "", ls_item = "";
DataRow[] myRow = dt.Select();
int i = 0;
if (columnNameList == null)
{
int cl = dt.Columns.Count;
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
colHeaders += dt.Columns[i].Caption.ToString() + "\r\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
}
else
{
int cl = columnNameList.Count;
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
colHeaders += columnNameList[i] + "\r\n";
}
else
{
colHeaders += columnNameList[i] + "\t";
}
}
}
HttpContext.Current.Response.Write(colHeaders);
//sw.Write(colHeaders);
foreach (DataRow row in myRow)
{
int cl = dt.Columns.Count;
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
ls_item += row[i].ToString() + "\r\n";
}
else
{
ls_item += row[i].ToString() + "\t";
}
}
HttpContext.Current.Response.Write(ls_item);
//sw.Write(ls_item);
ls_item = "";
}
HttpContext.Current.Response.End();
//sw.Close();
//fileStream.Close();
}
catch (Exception ex)
{
throw ex;
}
}