我在 mvc 中有一个 cshtml 视图,里面充满了 xml,例如:
@model myproject.net.Models.mymodel
@{
Layout = null;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; " + "filename=" +
Model.myusername.ToString() + "(" +
Model.mydate.Date.ToShortDateString() + ").xls");
}
<?xml version="1.0" encoding="utf-8"?>
<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
<Styles>
<Style ss:ID="s25">
<Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/>
<Borders>
<Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>
</Borders>
<Interior ss:Color="#FFA500" ss:Pattern="Solid"/>
</Style>
</Styles>
<ss:Worksheet ss:Name="Sheet1">
<ss:Table>
@if (Model.someNumerableContent.Count > 0)
{
<!-- MyContent -->
<ss:Row>
<ss:Cell><ss:Data ss:Type="String">Content Header</ss:Data></ss:Cell>
</ss:Row>
<ss:Row>
<ss:Cell><ss:Data ss:Type="String">SubHeader 1</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">SubHeader 2</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">SubHeader 3</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">SubHeader 4</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">SubHeader 5</ss:Data></ss:Cell>
</ss:Row>
foreach (var subContent in Model.someNumerableContent)
{
<ss:Row>
<ss:Cell><ss:Data ss:Type="String">@subContent.mydate.Date.ToShortDateString()</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">@subContent.number</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">@subContent.name</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">@subContent.surname</ss:Data></ss:Cell>
<ss:Cell><ss:Data ss:Type="String">@subContent.issue</ss:Data></ss:Cell>
</ss:Row>
}
<ss:Row> </ss:Row>
}
</ss:Table>
</ss:Worksheet>
</ss:Workbook>
我想将其转换为 .xls 文件并附加到邮件而不将其保存在任何地方。但无法弄清楚我怎么能做到这一点。我不能使用 office.interop 来解决我在服务器中遇到的一些限制,所以它不是我的选择。我只想通过 Xml 创建一个 .xls 文件并使用 .net 邮件发送它。到目前为止,我已经这样做了:
// Memory stream for the xml file
using (MemoryStream memoryStream = new MemoryStream())
{
// Can i use something like this?
byte[] contentAsBytes = Encoding.Default.GetBytes( View("ExportToExcel").ToString() );
memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);
// Set the position to the beginning of the stream.
memoryStream.Seek(0, SeekOrigin.Begin);
// Create attachment
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Xml;
contentType.Name = UserName + "(" + FileDate + ").xls";
// Attach
mail.Attachment = new Attachment(memoryStream, contentType);
}
那么我怎样才能做到这一点呢?