C# 从一个List集合中导出xls

woaimmwwyy 2010-07-21 03:06:31
Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("导出", System.Text.Encoding.UTF8)+ ".xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
StringWriter sw = new StringWriter();
sw.WriteLine("卡状态/t会员卡号/t卡密码");
sw.WriteLine("1'zwwlmzy'zhangdage");
sw.WriteLine("2'zwwlmzy1'zhangdage1");
sw.WriteLine("3'zwwlmzy2'zhangdage2");
Response.Write(sw);

导出的excel没有格式
如何设定他的格式
...全文
801 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
冬日 2011-07-08
  • 打赏
  • 举报
回复
到底用那一个
yingxiongmingduan 2010-07-21
  • 打赏
  • 举报
回复
都帖了这么多了,顶一下
wuyq11 2010-07-21
  • 打赏
  • 举报
回复
遍历list,打开excel模板
设置单元格格式
xlApp.get_Range(xlApp.Cells[3, 3], xlApp.Cells[3, 3]).Borders.LineStyle=1;

xlApp.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, 1]).Font.Size = 20;
xlApp.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, 1]).Font.Bold = true;

xlApp.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1,1]).ColumnWidth = 5;

xlApp.Cells.EntireColumn.AutoFit();
myrange.Cells.Interior.Color = System.Drawing.Color.FromArgb(200, 120, 130).ToArgb();
xlApp.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();

xlApp.get_Range(xlApp.Cells[3, 3], xlApp.Cells[3, 3]).Borders.Color = System.Drawing.Color.FromArgb(200,10,50).ToArgb();

xlApp.get_Range(xlApp.Cells[3, 3], xlApp.Cells[3, 3]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;

xlApp.get_Range(xlApp.Cells[3, 3], xlApp.Cells[3, 3]).Borders.Weight= XlBorderWeight.xlThick;
zjx198934 2010-07-21
  • 打赏
  • 举报
回复
下面一个我自己写的程序,把List格式化,你只需修改成你的list即可

public static string toExcel(HttpContext context)
{
XTBG_Entity.Person[] person = null;//我用的是实体数组,List一样
StringBuilder mStr = new StringBuilder();
int type = int.Parse(context.Request.Form["type"]);
int PageIndex = int.Parse(context.Request.Form["bbpageIndex"]);
int PageSize = int.Parse(context.Request.Form["pageSize"]);


mStr.Append("名字\t");
mStr.Append("姓氏\t");
mStr.Append("单位\t");
mStr.Append("移动电话\t");
mStr.Append("固定电话\t");
mStr.Append("电子邮箱\n");

if (type == 1)
{
int algId = int.Parse(context.Request.Form["AlgId"]);

person = XTBG_Logic.ALG.Alg.GetAllMembersByGroup(algId, PageIndex, PageSize);

}
else if (type == 2)
{
string TxName = context.Request.Form["TxName"].ToString();
person = XTBG_Logic.ALG.Alg.GetPersonByKeyword(TxName, PageIndex, PageSize);

}

foreach (XTBG_Entity.Person p in person)
{
mStr.Append(p.LastName + "\t");
mStr.Append(p.FirstName + "\t");
mStr.Append(p.OfficeName + "\t");
mStr.Append(p.PhoneNo + "\t");
mStr.Append(p.HomeTel + "\t");
mStr.Append(p.Email + "\n");
}



return XTBG_Entity.Tools.Excel.StringToExcel("自定义分组.xls", mStr.ToString(), context).ToString();//调用的是下面类中的方法

}


以下是一个我封装好了的类 可是直接使用,传入上面格式化好了的字符串

public class Excel
{
#region 将生成的Excel字符串导出
/// <summary>
/// 将生成的Excel字符串导出
/// </summary>
/// <param name="fileName"></param>
/// <param name="strExcel"></param>
/// <param name="context"></param>
/// <returns>-1 服务器不允许访问,其它 excel文件地址</returns>
public static string StringToExcel(string fileName, string strExcel, HttpContext context)
{
string IdentityAnalogue = System.Configuration.ConfigurationManager.AppSettings["IdentityAnalogue"];


string[] strArray = IdentityAnalogue.Split(';');
IdentityAnalogue IA = new IdentityAnalogue();
bool bo = IA.impersonateValidUser(strArray[0], strArray[1], strArray[2]);

if (!bo)
{
return "-1";
}



//if (bo)
//{
// return "-1";
//}


string urlPath = "http://" + context.Request.Url.Authority + context.Request.ApplicationPath + "/Excel";

string ExcelFolder = context.Request.PhysicalApplicationPath + "\\Excel";

DirectoryInfo m_dir = new System.IO.DirectoryInfo(ExcelFolder);

if (!m_dir.Exists)
{
m_dir.Create();
}

if ((m_dir.Attributes & FileAttributes.ReadOnly) != 0)
{
m_dir.Attributes = FileAttributes.Normal;

System.Security.AccessControl.DirectorySecurity dirsecurity = m_dir.GetAccessControl();

System.Security.AccessControl.FileSystemAccessRule fsa = new System.Security.AccessControl.FileSystemAccessRule(strArray[0], System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
dirsecurity.AddAccessRule(fsa);

}


FileInfo[] m_files = m_dir.GetFiles();
for (int i = 0; i < m_files.Length; i++)
{
if (m_files[i].LastWriteTime.AddDays(1) < System.DateTime.Now)
{
m_files[i].Delete();
}
}


System.IO.StreamWriter sw = new System.IO.StreamWriter(ExcelFolder + "\\" + fileName, false, System.Text.Encoding.Default);
sw.Write(strExcel);
sw.Flush();
sw.Close();

IA.undoImpersonation();

return urlPath + "/" + fileName;

}
#endregion

#region 保存Excel文件
/// <summary>
/// 保存Excel文件
/// </summary>
/// <param name="file"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string SaveExcel(HttpPostedFile file, string fileName, HttpContext context)
{
string IdentityAnalogue = System.Configuration.ConfigurationManager.AppSettings["IdentityAnalogue"];


string[] strArray = IdentityAnalogue.Split(';');
IdentityAnalogue IA = new IdentityAnalogue();
bool bo = IA.impersonateValidUser(strArray[0], strArray[1], strArray[2]);

if (!bo)
{
return "-1";
}

string urlPath = "http://" + context.Request.Url.Authority + context.Request.ApplicationPath + "/Excel";

string ExcelFolder = context.Request.PhysicalApplicationPath + "Excel";

DirectoryInfo m_dir = new System.IO.DirectoryInfo(ExcelFolder);

if (!m_dir.Exists)
{
m_dir.Create();
}

if ((m_dir.Attributes & FileAttributes.ReadOnly) != 0)
{
m_dir.Attributes = FileAttributes.Normal;

System.Security.AccessControl.DirectorySecurity dirsecurity = m_dir.GetAccessControl();

System.Security.AccessControl.FileSystemAccessRule fsa = new System.Security.AccessControl.FileSystemAccessRule(strArray[0], System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
dirsecurity.AddAccessRule(fsa);

}


FileInfo[] m_files = m_dir.GetFiles();
for (int i = 0; i < m_files.Length; i++)
{
if (m_files[i].LastWriteTime.AddDays(1) < System.DateTime.Now && m_files[i].Extension == ".xls")
{
m_files[i].Delete();
}
}

file.SaveAs(ExcelFolder + "\\" + fileName);



IA.undoImpersonation();

return ExcelFolder + "\\" + fileName;
}
#endregion
}
}
journey_q 2010-07-21
  • 打赏
  • 举报
回复

/// <summary>
/// 定义导出Excel的函数
/// </summary>
/// <param name="FileType"></param>
/// <param name="FileName"></param>
private void Export(string FileType, string FileName)
{
GridView1.AllowPaging = false;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
GridView1.Columns[GridView1.Columns.Count - 1].Visible = false;
GridView1.Columns[GridView1.Columns.Count - 2].Visible = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();

}


protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "Employee information.xls");
GridView1.AllowPaging = true;
}

net_xiaojian 2010-07-21
  • 打赏
  • 举报
回复

上面那些调用下面这个方法:
string fileName = Server.MapPath("~/Resource/ExcelFolder/") + GetDateString() + ".xls";

InitExcelFile(Response, fileName);

private void InitExcelFile(HttpResponse res, string fileName)
{
res.Clear();
res.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
res.ContentType = "application/ms-excel";
res.WriteFile(fileName);
//res.End();

string excelFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
Response.Redirect("/Resource/ExcelFolder/" + excelFileName, true);
}
net_xiaojian 2010-07-21
  • 打赏
  • 举报
回复
ExcelHelper.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Collections;

namespace WebLibrary
{
/// <summary>
/// 导出到excel文件。
/// </summary>
public class ExcelHelper
{
public static string GetXlsLine(params object[] aoField)
{
StringCollection items = new StringCollection();
for (int i = 0; i < aoField.Length; i++)
{
items.Add(aoField[i].ToString());
}
return GetXlsLine(items);
}

public static string GetXlsLine(ICollection items)
{
string sLineText = string.Empty;
foreach (Object item in items)
{
if (item != null) sLineText = sLineText + "\"" + item.ToString().Replace("\"", "") + "\"\t";
}
if (sLineText != string.Empty) sLineText = Left2(sLineText, 1);
return sLineText + "\r\n";
}

public static String[][] Parse(String sText)
{
if (sText == null || sText.Length == 0) return new String[0][] { };

String st = string.Empty;
ArrayList asLineText = new ArrayList(); // 行集合。其元素为行
ArrayList asCellText = new ArrayList(); // 单元格集合。其元素为一个单元格
bool bBeginWithQuote = false;
int iMaxColumns = 0;

for (int i = 0; i < sText.Length; i++)
{
char ch = sText[i];

if (ch == '\r' || ch == '\n')
{
if (bBeginWithQuote)
{
st += ch;
}
else
{
if (ch == '\r' && i + 1 < sText.Length && sText[i + 1] == '\n') i++;

asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;

iMaxColumns = (asCellText.Count > iMaxColumns ? asCellText.Count : iMaxColumns);
asLineText.Add(asCellText);
st = string.Empty;
asCellText = new ArrayList();
}
}
else if (ch == '\"')
{
if (bBeginWithQuote)
{
i++;
if (i >= sText.Length)
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
}
else
{
ch = sText[i];
if (ch == '\"')
{
st += ch;
}
else if (ch == ',')
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
}
else if (ch == '\r' || ch == '\n')
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;

iMaxColumns = (asCellText.Count > iMaxColumns ? asCellText.Count : iMaxColumns);
asLineText.Add(asCellText);
st = string.Empty;
asCellText = new ArrayList();

if (ch == '\r' && i + 1 < sText.Length && sText[i + 1] == '\n') i++;
}
else
{
throw new Exception("当字段以双引号开始时,禁止字段中存在单个双引号。字段号" + (asCellText.Count + 1) + ",列号:" + i);
}
}
}
else if (st.Length == 0)
{
bBeginWithQuote = true;
}
else
{
throw new Exception("双引号禁止存在于非双引号开始的字段。字段号:" + (asCellText.Count + 1));
}
}
else if (ch == ',')
{
if (bBeginWithQuote)
{
st += ch;
}
else
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
}
}
else
{
st += ch;
}

}

if (st.Length != 0)
{
if (bBeginWithQuote)
{
throw new Exception("最后一个字段以双引号开始,但未以双引号结束。");
}
else
{
asCellText.Add(st);
iMaxColumns = (asCellText.Count > iMaxColumns ? asCellText.Count : iMaxColumns);
asLineText.Add(asCellText);
}
}

String[][] asReturn = new String[asLineText.Count][];
for (int i = 0; i < asReturn.Length; i++)
{
asCellText = (ArrayList)asLineText[i];
asReturn[i] = new String[iMaxColumns];
for (int j = 0; j < iMaxColumns; j++)
{
asReturn[i][j] = asCellText[j].ToString();
}
}
return asReturn;
}

public static string Left2(string sInput, int iRightLength)
{
if (sInput == string.Empty) return string.Empty;
return sInput.Substring(0, sInput.Length - iRightLength);
}
}
}



调用

FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));

list = sdBll.GetPageList();
sw.Write(ExcelHelper.GetXlsLine("电池组信息", "电池组电流", "充放电状态", "电池组容量", "数据获取时间"));
foreach (Model.StringData model in list)
{
sw.Write(ExcelHelper.GetXlsLine(mBll.GetMenuName(model.ID), model.CHARGECURRENT / 10.0, model.STATE == 0 ? "否" : "是", model.SOC, model.DataDATE));
}
骑猪看海 2010-07-21
  • 打赏
  • 举报
回复
sw.WriteLine("1'zwwlmzy'zhangdage");
sw.WriteLine("2'zwwlmzy1'zhangdage1");
sw.WriteLine("3'zwwlmzy2'zhangdage2");

合成一句,加上table 给table设置边框
Peter200694013 2010-07-21
  • 打赏
  • 举报
回复
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
//fileName类似 LeaveSummary.xls
protected void Button1_Click(object sender, EventArgs e) { System.Web.HttpContext curContext = System.Web.HttpContext.Current; if (dt != null) { string filename = "档案全宗"; string name1 = filename; filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8); HttpResponse resp = System.Web.HttpContext.Current.Response; resp.Charset = "utf-8"; resp.Clear(); resp.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); resp.ContentEncoding = System.Text.Encoding.UTF8; resp.ContentType = "application/ms-excel"; string style =""+ ""; resp.Write(style); //resp.Write(ExportTable(list)); resp.Write(""); //VideoList = (List)Session["dbVideoList"]; for(int i=0;i"); resp.Write(""); resp.Write(""); resp.Write(""); resp.Write(""); resp.Write(""); } resp.Write("
" +"文件标题"+ "" + "档案类别" + "" +"发文日期" + "" +"文件链接" + "" +"备注" + "
" + dt.Rows[i]["FileName"]+ "" +dt.Rows[i]["type"]+ "" + dt.Rows[i]["fromtime"].ToString()+ "" + dt.Rows[i]["url"]+ "" + dt.Rows[i]["beizhu"]+ "
"); resp.Flush(); resp.End(); }

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧