公司项目,需要对一个列表做批量保存到Doc的功能。
后来通过架构人员协助,采用MemoryStream二进制流的方式保存为htm文档。
然后通过第3方的dll,ICSharpCode.SharpZipLib打包成zip文件。
抛弃doc的原因是流的形式保存为doc,office会解析为htm,但是Word样式很难维护,出现表格变粗的情况。
本地解压缩,从而实现批量保存的功能。
代码如下,
public void CreateZip() { List<MemoryStream> memList = new List<MemoryStream>(); for (int i = 0; i < 200; i++) { string a = @"<html> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf8'> <title>Ctrip.com Internet & Intranet - ViewEmail</title> </head> <body> <h1>test</h1> </body> </html>"; byte[] b = Encoding.GetEncoding("gb2312").GetBytes(a); MemoryStream mstream = new MemoryStream(); mstream.Write(b, 0, b.Length); memList.Add(mstream); } MemoryStream ms = new MemoryStream(); using (ZipFile zipF = ZipFile.Create(ms)) { zipF.BeginUpdate(); for (int i = 0; i < memList.Count; i++) { zipF.Add(new MemoryDataSource(memList[i].GetBuffer()), "a" + i.ToString() + ".htm"); } zipF.CommitUpdate(); } //将MemoryStream转换,否则发送时候可能出错 byte[] byteBuffer = ms.ToArray(); ms.Flush(); ms.Close(); Response.Clear(); Response.ContentType = "Application/zip"; Response.AppendHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("test" + DateTime.Now.ToString("yyyyMMdd") + ".zip", System.Text.Encoding.UTF8)); Response.BinaryWrite(byteBuffer); Response.End(); } protected void Button1_Click(object sender, EventArgs e) { CreateZip(); } class MemoryDataSource : IStaticDataSource { #region Constructors /// <summary> /// Initialise a new instance. /// </summary> /// <param name="data">The data to provide.</param> public MemoryDataSource(byte[] data) { data_ = data; } #endregion #region IDataSource Members /// <summary> /// Get a Stream for this <see cref="IStaticDataSource"/> /// </summary> /// <returns>Returns a <see cref="Stream"/></returns> public Stream GetSource() { return new MemoryStream(data_); } #endregion #region Instance Fields readonly byte[] data_; #endregion }