.net 操作office(excel、word)咋搞?
现在遇到麻烦了,我知道一个版本,就是通过修改
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode("下载文件.doc",System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-word";
这里面的参数,然后输出给客户端,这种看似很简单,但是,他貌似不是正规的Excel啊,有没有办法,在这个基础上,把他弄正规了,而不在服务器上安装office呢,有没有更好的办法?各位同行,你们都是怎么做的呢?最好能贴码,感激不尽啊。
在线等
------解决方案--------------------要正规的,必须调用Office的API,doc这些文档格式不是公开的
或者
Office Open XML
生成docx格式
参考手册和例子代码
http://msdn.microsoft.com/zh-cn/office/bb265236.aspx
------解决方案--------------------<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = new String[] { "测", "孟宪会" };
Repeater1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
String ExportFileName = "孟宪会导出 Word 测试";
if (Request.Browser.Browser.IndexOf("MSIE") > -1)
{
ExportFileName = HttpUtility.UrlEncode(ExportFileName, System.Text.UnicodeEncoding.GetEncoding("GB2312"));
}
ExportFileName += ".doc";
Response.Clear();
Response.BufferOutput = true;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + ExportFileName);
Response.ContentType = "application/ms-word";
Page.EnableViewState = false;
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
Literal header = new Literal();
header.Text = "<h2>文章标题</h2>";
Header.Controls.Add(header);
Header.RenderControl(textWriter);
this.Repeater1.RenderControl(textWriter);
Response.Write("<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns:m='http://schemas.microsoft.com/office/2004/12/omml' xmlns='http://www.w3.org/TR/REC-html40'><head></head><body lang=ZH-CN>" + stringWriter.ToString());
Response.End();
Response.Flush();
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table cellspacing="1" cellpadding="3" width="96%" align="center" border="1">
</HeaderTemplate>
<FooterTemplate>
</table></FooterTemplate>
<ItemTemplate>
<tr><td>测试啦</td><td>This is a 测试啊</td><td>
<%#Container.DataItem%></td></tr>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出成Word文档" />
</form>
</body>
</html>
------解决方案--------------------建议用NPOI
http://