接下来是批量导出word文档和批量打印word文件,批量导出word文档和批量打印word文件的思路差不多,只是批量打印不用打包压缩文件,而是把所有文件合成一个word,然后通过js来调用word,提交打印机,把word文档的内容都打印出来。
批量导出word文档需要用到ICSharpCode.SharpZipLib.dll 插件,思路是,先单独导出所勾选的数据的单个文档,保存到生成的临时目录下,再把同一个的人相关文档合并一个word文档,并删除已经合并的那个文档(不是合并后生成的文档),以姓名和编号命名生成后的文档,最后将临时目录下的所有文件打包压缩下载,并删除临时目录和临时目录下的所有文件(都是生成在服务器上,所以若文件太大,可能会慢)。批量导出是用form来提交所传的参数,并下载。(因为懒,不解释代码了)
首先新建一个空文档,插入书签,书签名为“p”(随便定义的),命名文件名为“test.doc”,保存在项目目录下。
相关js代码为:
/***************************************
* @methodname→批量导出word文档
* @createtime 2015-05-11
***************************************/
function AllExportWord(objid, tfile) {
var ckvalue = "", ntid = "", code = "", name = "";
var chkbox = $("input[type=checkbox][name=chk]:checked");
for (var i = ; i < chkbox.length; i++) {
ckvalue = ckvalue + chkbox[i].value + ","; //主键值
ntid = ntid + $(chkbox[i]).attr("data-ntid") + ","; //学生主键
code = code + $(chkbox[i]).attr("data-code") + ","; //胸卡号
name = name + $(chkbox[i]).attr("data-name") + ","; //姓名
}
if (ckvalue != "") {
ntid = ntid.substring(, ntid.length - );
code = code.substring(, code.length - );
name = name.substring(, name.length - );
$.ajax({
type: "POST",
url: "/NewStudent/BatchExportWord",
dataType: "json",
data: { tempFile: tfile, ntid: ntid },
async: false,
success: function (data) {
if (data.isOK) {
var count = ntid.split(',').length;
if (count == data.ls.length && count > ) {
DownLoadWord(objid, tfile, ntid, code, name, true);
}
else {
if (confirm("选择导出的数据中包含没有学习记录的数据,是否确认导出或打印?")) {
DownLoadWord(objid, tfile, ntid, code, name, true);
}
}
}
else {
alert(data.msg);
}
}
});
}
else {
alert("请选择数据!");
}
}
/***************************************
* @methodname→批量导出word文档
* @createtime 2015-05-11
***************************************/
function BatchExportWord(objid, tfile) {
var ckvalue = "", ntid = "", code = "", name = "";
var chkbox = $("input[type=checkbox][name=chk]:checked");
for (var i = ; i < chkbox.length; i++) {
ckvalue = ckvalue + chkbox[i].value + ","; //主键值
ntid = $(chkbox[i]).attr("data-ntid"); //学生主键
code = $(chkbox[i]).attr("data-code"); //胸卡号
name = $(chkbox[i]).attr("data-name"); //姓名
}
if (ckvalue != "") {
ckvalue = ckvalue.substring(, ckvalue.length - ); //去掉最后一个逗号
$.ajax({
type: "POST",
url: "/NewStudent/BatchExportWord",
dataType: "json",
data: { tempFile: tfile },
async: false,
success: function (data) {
if (data.isOK) {
DownLoadWord(objid, tfile, ntid, code, name, false)
}
else {
alert(data.msg);
} }
});
}
else {
alert("请选择数据!");
}
}
/*************************************************
* @methodname→只能通过流的方式批量导出word文档
在页尾添加form,通过提交form表单才能下载
* @createtime 2015-05-12
*************************************************/
function DownLoadWord(idName, tfile, ntid, code, name, isAll) {
$("body").find("form.#form1").remove();
var form = "<form id='form1'></form>";
var input = "<input />";
var input1 = "", input2 = "", input3 = "", input4 = "", input5 = "", input6 = "";
input1 = $(input); input1.attr("type", "hidden"); input1.attr("name", "tempFile"); input1.attr("value", tfile);
input2 = $(input); input2.attr("type", "hidden"); input2.attr("name", "ntid"); input2.attr("value", ntid);
input3 = $(input); input3.attr("type", "hidden"); input3.attr("name", "code"); input3.attr("value", code);
input4 = $(input); input4.attr("type", "hidden"); input4.attr("name", "name"); input4.attr("value", name);
input5 = $(input); input5.attr("type", "hidden"); input5.attr("name", "isAll"); input5.attr("value", isAll);
input6 = $(input); input6.attr("type", "hidden"); input6.attr("name", "idName"); input6.attr("value", idName);
$("body").append(form); //将表单放置在web中
//添加表单属性
$("#form1").attr("style", "display:none");
$("#form1").attr("target", "");
$("#form1").attr("method", "post");
$("#form1").attr("action", "/NewStudent/DownLoadWord"); //添加input到表单里
$("#form1").append(input1)
$("#form1").append(input1);
$("#form1").append(input2);
$("#form1").append(input3);
$("#form1").append(input4);
$("#form1").append(input5);
$("#form1").append(input6);
$("#form1").submit();
}
js
相关后台代码如下:
#region 压缩文件及文件夹
/// <summary>
/// 压缩文件及文件夹
/// </summary>
public class CompressFileZip
{
private ZipOutputStream zos = null;
private string strBaseDir = ""; #region 临时文件夹名称
/// <summary>
/// 临时文件夹名称
/// </summary>
/// <param name="name">学生名称</param>
/// <param name="value">学生卡号</param>
/// <returns></returns>
public string FolderName(string name, string value)
{
string tempName = "";
if (!string.IsNullOrEmpty(name))
{
tempName = name;
if (!string.IsNullOrEmpty(value))
tempName += "_" + value;
tempName += "_" + DateTime.Now.ToString("yyyyMMddHHmm");
}
else
{
tempName = DateTime.Now.ToString("yyyyMMddHHmmss"); //临时文件夹名称
}
return tempName;
}
#endregion #region 创建临时文件夹
/// <summary>
/// 创建临时文件夹
/// </summary>
/// <param name="name">学生名称</param>
/// <param name="value">学生卡号</param>
/// <returns></returns>
public string CreateTempFolder(string name, string value = null)
{
//遍历服务器指定文件夹下的所有文件
string path = "UploadFile";
string serverPath = WordFilePath.GetFilePath(path);
string tempName = "";
if (!string.IsNullOrEmpty(value))
tempName = FolderName(name, value);
else
tempName = name;
string tempFolder = Path.Combine(serverPath, tempName);
Directory.CreateDirectory(tempFolder); //创建临时文件夹
//DirectoryInfo folder = new DirectoryInfo(serverPath);
return tempFolder + "\\";
}
#endregion #region 添加文件到压缩文件中
/// <summary>
/// 添加文件到压缩文件中
/// </summary>
/// <param name="PathStr">路径</param>
public void addZipEntry(string PathStr)
{
DirectoryInfo di = new DirectoryInfo(PathStr);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName);
}
foreach (FileInfo item in di.GetFiles())
{
FileStream fs = System.IO.File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
string strEntryName = item.FullName.Replace(strBaseDir, "");
ZipEntry entry = new ZipEntry(strEntryName);
zos.PutNextEntry(entry);
zos.Write(buffer, , buffer.Length);
fs.Close();
}
}
#endregion #region 输出下载压缩包
/// <summary>
/// 输出下载压缩包
/// </summary>
/// <param name="response">页面响应</param>
/// <param name="strPath">文件所在的路径</param>
/// <param name="strFileName">压缩文件名</param>
/// <param name="strExt">压缩文件的扩展名</param>
public void dlZipDir(HttpResponseBase response, string strPath, string strFileName, string strExt = null)
{
if (string.IsNullOrEmpty(strExt))
strExt = ".zip"; //默认压缩文件扩展名
MemoryStream ms = null;
response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + strExt);
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir = strPath + "\\";
addZipEntry(strBaseDir);
zos.Finish();
zos.Close();
response.Clear();
response.BinaryWrite(ms.ToArray());
//删除临时目录下的所有文件
DeleteTempFiles(strPath);
//删除空目录
Directory.Delete(strPath);
response.End();
}
#endregion #region 保存文件到临时文件夹中
/// <summary>
/// 保存文件到临时文件夹中
/// </summary>
/// <param name="content">将流内容写入字节组</param>
/// <param name="SaveName">保存的文件名</param>
/// /// <param name="dirPath">保存路径</param>
/// <param name="fileExtend">保存的文件扩展名</param>
/// <returns></returns>
public void SaveFile(byte[] content, string SaveName, string dirPath, string fileExtend = null)
{ if (string.IsNullOrEmpty(fileExtend))
fileExtend = ".doc"; //文件扩展名默认是word文档
try
{
DateTime dt = DateTime.Now;
//设置文件夹路径
//directory = CreateTempFolder(strName, strCode);
//文件保存完整路径
string path = dirPath + SaveName + fileExtend;
//验证文件夹是否存在 不存在则创建
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
//以创建文件的方式写入内容
FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
BinaryWriter w = new BinaryWriter(fs);
w.Write(content);
w.Close();
fs.Close();
}
catch (Exception ex)
{
throw new System.IO.FileNotFoundException("目录:" + dirPath + "没有找到!");
}
}
#endregion #region 删除临时目录下的所有文件
/// <summary>
/// 删除临时目录下的所有文件
/// </summary>
/// <param name="tempPath">临时目录路径</param>
private void DeleteTempFiles(string tempPath)
{
DirectoryInfo directory = new DirectoryInfo(tempPath);
try
{
foreach (FileInfo file in directory.GetFiles())
{
if (file.Attributes.ToString().IndexOf("ReadOnly") != -)
{
file.Attributes = FileAttributes.Normal;
}
System.IO.File.Delete(file.FullName);
}
}
catch (Exception)
{
throw;
}
}
#endregion #region 获取指定文件夹下的所有文件
/// <summary>
/// 获取指定文件夹下的所有文件
/// </summary>
/// <param name="Folder">文件夹名称</param>
/// <param name="strName">文件夹下所包含指定文件名的文件</param>
/// <returns></returns>
public List<string> GetFileList(string Folder, string strName = null)
{
List<string> lsFile = new List<string>();
if (!string.IsNullOrEmpty(Folder))
{
Folder = WordFilePath.GetFilePath("UploadFile", Folder + "\\");
DirectoryInfo di = new DirectoryInfo(Folder);
foreach (FileInfo item in di.GetFiles())
{
if (!string.IsNullOrEmpty(strName))
{
if (item.FullName.Contains(strName))
lsFile.Add(item.FullName);
}
else
lsFile.Add(item.FullName);
}
}
return lsFile;
}
#endregion }
#endregion #region 插入文档
public class InsertFile
{
#region 在书签位置插入另一个文档的内容
/// <summary>
/// 使用DocumentBuilder对象插入一些文档对象,如插入书签,插入文本框,插入复选框
/// 插入一个段落,插入空白页,追加或另一个word文件的内容等。
/// </summary>
/// <param name="doc">载入模板</param>
/// <param name="tempFile"></param>
/// <param name="mark">载入模版名称</param>
/// <param name="lsFile"></param>
public static void InsertDoc(Document doc, string mark, List<string> lsFile, string SaveName = null)
{
string savePath = "";
var builder = new DocumentBuilder(doc);
if (!string.IsNullOrEmpty(SaveName))
SaveName = SaveName.Substring(, SaveName.LastIndexOf("_"));
Document doc1;
for (int i = ; i < lsFile.Count; i++)
{
if (i == )
savePath = lsFile[i].Substring(, lsFile[i].LastIndexOf('\\') + );
doc1 = new Document(lsFile[i]);//新文档
var bookmark = doc.Range.Bookmarks[mark];
//清空书签的文本
//bookmark.Text = "";
//定位到指定位置进行插入操作
builder.MoveToBookmark(mark, false, false);
InsertDocument(bookmark.BookmarkStart.ParentNode, doc1);
//doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
//doc1.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); System.IO.File.Delete(lsFile[i]); //删除已经插入的文件
}
if (!string.IsNullOrEmpty(SaveName))
doc.Save(savePath + SaveName + ".doc");
}
#endregion #region 插入文档
/// <summary>
/// 插入文档
/// </summary>
/// <param name="insertAfterNode">节点在目标文件中的内容后插入。这个节点应该是一个块级节点(段落或表格)。</param>
/// <param name="srcDoc">插入文档</param>
private static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
// 确保插入点是一个段落或表格。
if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
(!insertAfterNode.NodeType.Equals(NodeType.Table)))
throw new ArgumentException("插入的目的节点应该是一个段落或表格。"); // 插入到目标段落
CompositeNode dstStory = insertAfterNode.ParentNode;
NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting); //在源文件中循环
foreach (Section srcSection in srcDoc.Sections)
{
foreach (Node srcNode in srcSection.Body)
{
// 跳过空节点
if (srcNode.NodeType.Equals(NodeType.Paragraph))
{
Paragraph para = (Paragraph)srcNode;
if (para.IsEndOfSection && !para.HasChildNodes)
continue;
}
// 插入到目标文档
Node newNode = importer.ImportNode(srcNode, true);
// 参考节点后插入新节点
dstStory.InsertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
#endregion
}
#endregion
Code
页面调用的方式如下:
<input id="Export" type="button" class="s_btn" value="批量导出" onclick="AllExportWord(this.id, '接收进修生手册导出模板')" />
<input id="Print" type="button" class="s_btn" value="批量打印" onclick="AllExportWord(this.id, '接收进修生手册导出模板')" />
<input type="checkbox" name="chk" id="chk" value='@item.CardNo' data-ntid="@item.NTID" data-code="@item.CardNo" data-name="@item.NTName" /></td>
Html
这里的this.id是传当前请求的按钮的id,因为调用的方法都一样,所以同时传id,加以区分页面的请求,以实现不同的功能。
controller调用的方法:
#region 批量下载文件前的验证
/// <summary>
/// 批量下载文件前的验证
/// </summary>
/// <param name="tempFile">模板</param>
/// <param name="ntid">学生主键</param>
/// <returns></returns>
public JsonResult BatchExportWord(string tempFile, string ntid = null)
{
bool isOK = false;
string msg = "";
string strpath = "Content/templates";
List<string> ls = new List<string>();
if (!string.IsNullOrEmpty(tempFile))
{
if (Path.GetExtension(tempFile) != ".doc")
tempFile = tempFile + ".doc";
isOK = WordFilePath.ExistFile(strpath, tempFile);
if (!isOK)
msg = "导出的模板不存在!";
else
{
if (!string.IsNullOrEmpty(ntid))
{
string[] strNTID = ntid.Split(',');
for (int i = ; i < strNTID.Length; i++)
{
NameValueCollection nvc = new NameValueCollection();
nvc.Add(GetPropertyName<Model.MajorCycle>(m => m.NTID), strNTID[i]);
IList<Model.MajorCycle> lsMCycle = new BLL.MajorCycle().GetModelList<Model.MajorCycle>(nvc);
if (lsMCycle.Count > )
ls.Add(string.Join(",", lsMCycle.Select(m => m.ID)));
}
}
}
}
else
{
msg = "导出的模板为空!";
}
return Json(new { isOK = isOK, msg = msg, ls = ls });
}
#endregion #region 下载压缩包
/// <summary>
/// 下载压缩包
/// </summary>
/// <param name="tempFile">模板</param>
/// <param name="ntid">学生主键</param>
/// <param name="code">学生编号</param>
/// <param name="name">学生名称</param>
/// <param name="isAll">是否全部导出</param>
/// <param name="idName">请求按钮id名称</param>
/// <returns></returns>
public FileContentResult DownLoadWord(string tempFile, string ntid, string code, string name, string isAll, string idName)
{
CompressFileZip fileZip = new CompressFileZip();
string saveName = "", dirPath = "", GzipFileName = "", mid = "", stype = "", sequence = "";
Document doc = new Document();
var docStream = new MemoryStream();
if (!string.IsNullOrEmpty(ntid))
{
string[] strNTID = ntid.Split(',');
string[] strCode = code.Split(',');
string[] strName = name.Split(',');
for (int i = ; i < strNTID.Length; i++)
{
if (i == ) //第一次时创建临时文件夹
{
if (!string.IsNullOrEmpty(isAll) && isAll == "true")
GzipFileName = fileZip.FolderName(tempFile.Substring(, tempFile.IndexOf("生") + ), "");
else
GzipFileName = fileZip.FolderName(strName[i], strCode[i]);
dirPath = fileZip.CreateTempFolder(GzipFileName);
}
NameValueCollection nvc = new NameValueCollection();
nvc.Add(GetPropertyName<Model.MajorCycle>(m => m.NTID), strNTID[i]);
IList<Model.MajorCycle> lsMCycle = new BLL.MajorCycle().GetModelList<Model.MajorCycle>(nvc);
if (lsMCycle.Count > ) //如果不以这方式,则没有学习记录的数据导出来会是一个空的压缩包,什么文件也没有
{
mid = string.Join(",", lsMCycle.Select(m => m.MajorID)); // 轮转科室id
stype = lsMCycle[].StudentType.ToString().Trim(); // 学生类型
sequence = string.Join(",", lsMCycle.Select(m => m.Sequence)); // 轮转次数
}
string[] midArr = mid.Split(',');
string[] sequenceArr = sequence.Split(',');
mid = ""; sequence = "";
for (int j = ; j < midArr.Length; j++)
{
saveName = strName[i] + "_" + strCode[i] + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
WordHelper wordhelper = new WordHelper(tempFile);
getWordInfo(wordhelper, tempFile, strNTID[i], stype, midArr[j], sequenceArr[j]);
fileZip.SaveFile(wordhelper.ExportDoc().ToArray(), saveName, dirPath);
}
if (!string.IsNullOrEmpty(isAll) && isAll == "true" && idName == "Export")
{
doc = new Document(WordFilePath.GetFilePath("Content/templates", "test.doc"));
InsertFile.InsertDoc(doc, "p", fileZip.GetFileList(GzipFileName, strName[i]), saveName);
} }
if (idName == "Export")
fileZip.dlZipDir(Response, WordFilePath.GetFilePath("UploadFile", GzipFileName), GzipFileName); //压缩下载
} if (idName == "Print") //打印
{
doc = new Document(WordFilePath.GetFilePath("Content/templates", "test.doc"));
InsertFile.InsertDoc(doc, "p", fileZip.GetFileList(GzipFileName));
doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
Directory.Delete(WordFilePath.GetFilePath("UploadFile", GzipFileName));
}
return base.File(docStream.ToArray(), "application/msword", GzipFileName);
}
#endregion
导出的效果如下图: 生成的临时文件夹:
同一人的首先生成单个文件
将两个文件合并成一个文件,以姓名和编号命名,同时删除合并前生成的那两个文件:
循环生成 下一个人的单个文档
合并文件,以姓名和编号命名,同时删除合并前的文件:
打包压缩合并后的这两个文件,并下载:
打印的效果如下图: 将所有人的有关文档都生成单个文件
最后合并成一个文件,并输出: