MVC 下 打包多个word到压缩包

第一步 引入dll

控制器代码

     /// <summary>
        /// 导出Word表格
        /// </summary>
        /// <param name="Pyaid">选中数据ID</param>
        /// <param name="type">是否结束的报告(状态)</param>
        public void ToWord(string[] Pyaid, int type)

        {
            //获取选中的id
            string[] j = Pyaid[0].Split(',');
            AchievementExpand achieve = new AchievementExpand();
            if (Pyaid != null)
            {
                int[] output = Array.ConvertAll<string, int>(j, delegate (string s) { return int.Parse(s); });
                if (output.Length > 0)
                {

                    string filePath = null;
                    for (int i = 0; i < output.Length; i++)
                    {

                        if (type == 0)
                        {
                            //获取所有成绩信息
                            string sql = @"SELECT su.subject_name,  syp.AddTime, us.user_name, ac.*, st.student_no FROM Achievement ac
                           LEFT JOIN student_info st ON ac.stu_id = st.student_id
                            left join class_info sy ON sy.class_id=ac.cla_id
                           left join user_info  us on us.user_id=sy.class_teacher
                             left join Sy_PracticalTraining syp on syp.ID=ac.pya_id
                             left join subject su on su.subject_id=sy.class_subject
                           WHERE ac.IsEnd=0 and  ac.ID=" + output[i];
                            achieve = entity.Database.SqlQuery<AchievementExpand>(sql).FirstOrDefault();
                            // 创建HSSFWorkbook对象(excel的文档对象)

                        }
                        else
                        {
                            //获取历史成绩信息
                            string sql = @"SELECT su.subject_name,  syp.AddTime, us.user_name, ac.*, st.student_no FROM Achievement ac
                           LEFT JOIN student_info st ON ac.stu_id = st.student_id
                            left join class_info sy ON sy.class_id=ac.cla_id
                           left join user_info  us on us.user_id=sy.class_teacher
                             left join Sy_PracticalTraining syp on syp.ID=ac.pya_id
                             left join subject su on su.subject_id=sy.class_subject
                           WHERE ac.IsEnd=1 and ac.ID=" + output[i];
                            achieve = entity.Database.SqlQuery<AchievementExpand>(sql).FirstOrDefault();

                        }
                        Random rd = new Random();
                        string fileName = achieve.PyaName + "-" + achieve.student_no + ".doc";
                        //存储路径
                        string path = Server.MapPath("~/UpFiles/DoxlFiles/") + fileName;
                        //创建字符输出流
                        StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8);
                        //需要导出的内容
                        string str = "";
                        str += "<html><head><title>实训报告</title></head><body>";
                        str += "<div style='text-align:center'>实训报告</div>";
                        str += "<table border='1'  cellspacing='0px'style='border - collapse:collapse; text - align:center'><tr style='background:#bec6b9'>";
                        str += "<th>学号</th>";
                        str += "<th>姓名</th><th>班级</th><th>专业</th><th>指导教师</th><th>实训名称</th><th>流程得分</th><th>教师评分</th> <th>利润率</th> <th>总分</th></tr><tr>";
                        str += "<td>" + achieve.student_no + "</td>";
                        str += "<td>" + achieve.Stu_Name + "</td><td>" + achieve.Claa_Name + "</td><td>" + achieve.subject_name + "</td><td>" + achieve.user_name + "</td><td>" + achieve.PyaName + "</td><td>" + achieve.Processscore + "</td><td>" + achieve.Teacherrating + "</td><td>" + achieve.rate + "</td><td>" + (achieve.Processscore + achieve.Teacherrating) + "</td></tr>";
                        str += "</table></body></html>";
                        //写入
                        sw.Write(str);
                        sw.Close();
                        //把所有文件名放在字符串里用 | 隔开
                        filePath += fileName + "|";
                    }
                    //调用压缩
                    DownLoadFiles(filePath);
                }
            }

        }

 

        ///<summary>
        /// 批量打包下载压缩
        /// </summary>
        /// <param name="fileName">文件名称</param>
        public void DownLoadFiles(string filePath)
        {
            int length = filePath.Length;
            //截取除最后一位的 | 前面所有字符
            filePath = filePath.Substring(0, length - 1);
            //所有放在服务器的文件的名字集合
            List<string> filePaths = filePath.Split('|').ToList();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = null;
            using (ZipFile file = ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
                //文件名集合循环
                filePaths.ForEach(t =>
                {
                    string s = Server.MapPath(@"~/UpFiles/DoxlFiles/" + t);
                    //循环把文件加入压缩包
                    file.Add(s);
                });
                file.CommitUpdate();
                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }
        
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("批量下载实训报告.zip", System.Text.Encoding.UTF8));
            Response.BinaryWrite(buffer);
            Response.Flush();
            Response.End();
            //循环删除放在服务器的模板
            filePaths.ForEach(t =>
            {
                FileInfo fi = new FileInfo(Server.MapPath("~/UpFiles/DoxlFiles/" + t));//删除存在项目文件夹的模板
                fi.Delete();
            });
        }
DownLoadFiles
    /// <summary>
    /// 压缩包帮助类
    /// </summary>
    public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform

    {
        #region INameTransform 成员

        public string TransformDirectory(string name)
        {
            return null;
        }

        public string TransformFile(string name)
        {
            return Path.GetFileName(name);
        }

        #endregion
    }
MyNameTransfom 帮助类

 

posted @ 2019-03-27 18:02  上铺的那个人  阅读(360)  评论(0编辑  收藏  举报