将数据从通用列表导出到Asp.net中的现有Excel文件 [英] Export data from Generic List to Existing Excel File in Asp.net
本文介绍了将数据从通用列表导出到Asp.net中的现有Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮助我解决这个问题吗?...
下面的代码用于使用通用列表中的数据创建一个新的excel文件...我不想创建一个新的excel文件..i只需要将数据添加到现有的excel文件中即可.
Could anyone help me to solve this issue....
The below code is for creating a new excel file with data from generic list...I dont want to create a new excel file ..i just needed to add data to an existing excel file.
protected void Button1_Click(object sender, EventArgs e)
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee(20, "Ranjith"));
empList.Add(new Employee(23, "Rakesh"));
empList.Add(new Employee(30, "Ram"));
// take excel FileName and the Exported List
Export("Ranjith", empList);
}
public void Export(string fileName, List<Employee> empList)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName + ".xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the List
Table table = new Table();
TableRow row = new TableRow();
foreach (PropertyInfo proinfo in new Employee(1,"Name").GetType().GetProperties())
{
TableHeaderCell hcell = new TableHeaderCell();
hcell.Text = proinfo.Name;
row.Cells.Add(hcell);
}
table.Rows.Add(row);
// add each of the data item to the table
foreach (Employee emp in empList)
{
TableRow row1 = new TableRow();
TableCell cellAge = new TableCell();
cellAge.Text = "" + emp.Age;
TableCell cellName = new TableCell();
cellName.Text = "" + emp.Name;
row1.Cells.Add(cellAge);
row1.Cells.Add(cellName);
table.Rows.Add(row1);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
推荐答案
您正在创建HTML Excel文件,很难直接添加更多行.
您可以使用一些第三方工具来制作excel文件/添加行等.
您可以尝试以下操作:
ClosedXML-OpenXML的简便方法
http://closedxml.codeplex.com/ [ ^ ]
You are creating a HTML Excel File which very hard to add more rows directly.
You can use some third party tools to make an excel file / to add rows etc.
You can try this:
ClosedXML - The easy way to OpenXML
http://closedxml.codeplex.com/[^]
这篇关于将数据从通用列表导出到Asp.net中的现有Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文