我如何在不需要安装Excel的计算机上使用C#创建Excel电子表格?
我如何在不需要安装Excel的计算机上使用C#创建Excel电子表格?
我同意生成XML电子表格,在这里提供一个示例,演示如何在C# 3中执行此操作(每个人都只在VB 9中博客发布它 :P)http://www.aaron-powell.com/linq-to-xml-to-excel
我想再添加一个第三方解决方案的参考,可以直接解决您的问题:http://www.officewriter.com
(免责声明:我在SoftArtisans工作,这是OfficeWriter的制造公司)
public class GridViewExportUtil
{
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// 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();
}
}
}
/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
}
嗨,这个解决方案是将您的网格视图导出到Excel文件中,它可能会帮助您。
从C#创建Excel文件的最简单和最快的方法是使用Open XML Productivity Tool。该工具随Open XML SDK安装一起提供。该工具将任何Excel文件反向工程为C#代码。然后可以使用该C#代码重新生成该文件。
涉及的过程概述如下:
DesiredLook.xlsx
。DesiredLook.xlsx
,并单击顶部附近的Reflect Code按钮。
作为额外奖励,此方法适用于任何Word和PowerPoint文件。作为C#开发人员,您将更改代码以适应自己的需求。
我已经在Github上开发了一个简单的WPF应用程序,可以在Windows上运行。有一个叫做GeneratedClass
的占位符类,您可以将生成的代码粘贴到其中。如果您返回文件的上一个版本,它会生成一个像这样的Excel文件:
一些第三方组件供应商,例如Infragistics或Syncfusion,提供非常出色的Excel导出功能,无需安装Microsoft Excel。
由于这些供应商还提供高级UI网格组件,因此如果您想要使Excel导出的样式和布局模仿应用程序用户界面中网格的当前状态,则这些组件特别方便。
如果您的导出旨在在服务器端执行,重点是要导出数据,并且与用户界面无关联,则我会选择其中一个免费的开源选项(例如ExcelLibrary)。
我之前曾参与过尝试在Microsoft Office套件上使用服务器端自动化的项目。基于这个经验,我强烈不建议采用那种方法。
using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
helper.CurrentSheetName = "Sheet1";
helper.CurrentPosition = new CellRef("C3");
//the template xlsx should contains the named range "header"; use the command "insert"/"name".
helper.InsertRange("header");
//the template xlsx should contains the named range "sample1";
//inside this range you should have cells with these values:
//<name> , <value> and <comment>, which will be replaced by the values from the getSample()
CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"});
helper.InsertRange(sample1, getSample());
//you could use here other named ranges to insert new cells and call InsertRange as many times you want,
//it will be copied one after another;
//even you can change direction or the current cell/sheet before you insert
//typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
helper.DeleteSheet("Sheet3");
}
样例看起来像这样:
private IEnumerable<List<object>> getSample()
{
var random = new Random();
for (int loop = 0; loop < 3000; loop++)
{
yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
}
}
以下是使用LINQ to XML的一种方法,附有示例代码:
这个方法有点复杂,因为你需要导入命名空间等等,但它确实可以避免任何外部依赖。
(当然,这是VB .NET而不是C#,但你可以将VB .NET的内容隔离到自己的项目中使用XML Literals,并在C#中完成其他所有操作。)
你有没有试过Sylk?
我们以前在经典ASP中生成Sylk格式的Excel表格,现在我们正在寻找一种新的Excel生成器。
Sylk的优点是可以格式化单元格。