Asp.Net 自定义word格式,批量打印,生成word文件

时间:2021-02-02 12:00:03
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Word = Microsoft.Office.Interop.Word;
using HY.Common.Configuration;
using System.Net;
using System.Text;
using System.IO;
using HY.Common.Utils;
using System.Data;
using HC.ReportPluginsHandler.BusinessComponent;
using Microsoft.Office.Interop.Word;

namespace HC.Web.PluginsFor2.ReportWeb.Page.LoanReimReqiestForm
{
public partial class LoanReimlPrint : System.Web.UI.Page
{
LoanReimlPrintBC eab
= new LoanReimlPrintBC();
LoanReimReqiestFormBC bc
= new LoanReimReqiestFormBC();
protected void Page_Load(object sender, EventArgs e)
{
HY.Common.Utils.Logger.Log.Info(
"开始批量打印");
object filename = "";
HY.Common.Utils.Logger.Log.Info(
"filename:" + filename);
Object Nothing
= System.Reflection.Missing.Value;
HY.Common.Utils.Logger.Log.Info(
"Nothing:" + Nothing);
//Word.Application WordApp = new Word.ApplicationClass();//实例化word
Word.Application WordApp = new Word.ApplicationClass();
HY.Common.Utils.Logger.Log.Info(
"WordApp:" + WordApp);
Word._Application oWord
= new Word.Application();
//创建Word文档
Word._Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
if (WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdOutlineView)
{

WordApp.ActiveWindow.ActivePane.View.Type
= WdViewType.wdPrintView;
}

WordApp.ActiveWindow.View.SeekView
= WdSeekView.wdSeekCurrentPageHeader;

WordApp.Selection.HeaderFooter.LinkToPrevious
= false;

WordApp.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle
= Word.WdLineStyle.wdLineStyleNone; //wdlinestyle.wdlinestylenone;
WordDoc.ActiveWindow.ActivePane.Selection.InsertAfter("\n\n………………………………………………………………………财务装订线……………………………………………………………………\n");

//跳出页眉设置
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;

try
{
SetPage(WordApp, WordDoc,
"竖版", 20.3, 29.7, 1, 1, 1, 1);
HY.Common.Utils.Logger.Log.Info(
"WordDoc:" + WordDoc);
string name = "报销报表" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToLongTimeString().Replace(":", "") + ".docx";//创建生成文件名字
HY.Common.Utils.Logger.Log.Info("name" + name);
string CreateFilePath = ConfigurationManager.AppSettings["CreateFilePath"];
HY.Common.Utils.Logger.Log.Info(
"CreateFilePath" + CreateFilePath);
filename
= CreateFilePath + name; //文件保存路径
HY.Common.Utils.Logger.Log.Info("filename" + filename);
string PrintType = Context.Request["PrintType"].ToString();
int index = 0;

string[] SerialNumberArr = Context.Request["Folio"].Substring(0, Context.Request["Folio"].ToString().Length - 1).Split(',');
string[] ProcInstIDArr = Context.Request["ProcInstID"].Substring(0, Context.Request["ProcInstID"].ToString().Length - 1).Split(',');//挂账Id
string[] ProcName = Context.Request["ProcName"].Substring(0, Context.Request["ProcName"].ToString().Length - 1).Split(',');//付款Id

for (int i = 0; i < ProcInstIDArr.Length; i++)
{
#region 生成条形码
Logger.Log.Info(
"***********************Start****************************");
string sn = SerialNumberArr[i];
System.Guid guid
= new Guid();
guid
= Guid.NewGuid();
string str = guid.ToString();
CreateBmp(sn, CreateFilePath, str);
Logger.Log.Info(
"***********************End****************************");
#endregion
DataSet ds
= eab.GetBatchPrint(ProcInstIDArr[i], ProcName[i]);
PrintWord(Nothing, WordDoc, CreateFilePath, ProcInstIDArr.Length, ProcName[i], i, sn, str, ds,index);
index
++;
}

WordDoc.SaveAs(
ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordApp
= null;


HY.Common.Utils.Logger.Log.Info(
"SaveAs" + filename);

}
catch (Exception ex)
{

HY.Common.Utils.Logger.Log.Info(
"error" + ex.ToString());
}
finally
{
WordDoc.Close(
ref Nothing, ref Nothing, ref Nothing);
oWord.Quit(
ref Nothing, ref Nothing, ref Nothing);
KillWordProcess();
}
Response.Redirect(
"/PluginsFor2/ProjectWeb/Page/ExcelBatchApproval/DownLoadFilePrint.aspx?filename=" + System.Web.HttpUtility.UrlEncode(filename.ToString()));//將檔案名稱傳送到另一個頁面
Context.Response.Write("{success:'true',fileName:'" + filename.ToString() + "'}");
}

private static void PrintWord(Object Nothing, Word._Document WordDoc, string CreateFilePath, int ProcInstIDArrLenth, string ProcName, int i, string sn, string str, DataSet ds,int index)
{
System.Data.DataTable dtBasicInfo
= ds.Tables[0];//基本信息
System.Data.DataTable dtAllHistorysInfo = ds.Tables[4];//审批历史记录
dtAllHistorysInfo = ds.Tables[7];

System.Data.DataTable dtHistorysInfo
= new System.Data.DataTable();
dtHistorysInfo.Columns.Add(
"CZXMJL");//由于用不到列名,所以随便写,只要保证列数够用就可
dtHistorysInfo.Columns.Add("BMXMJL");
dtHistorysInfo.Columns.Add(
"ZYSP");
dtHistorysInfo.Columns.Add(
"CZSP");
dtHistorysInfo.Columns.Add(
"CZXMJL2");
dtHistorysInfo.Columns.Add(
"BMXMJL2");
dtHistorysInfo.Columns.Add(
"ZYSP2");
dtHistorysInfo.Columns.Add(
"CZSP2");
if (dtAllHistorysInfo.Rows.Count > 0)
{
string[] hiArr = new string[8];
hiArr[
0] = "审批人";
hiArr[
1] = "流程节点";
hiArr[
2] = "审批意见";
hiArr[
3] = "审批时间";
hiArr[
4] = "审批人";
hiArr[
5] = "流程节点";
hiArr[
6] = "审批意见";
hiArr[
7] = "审批时间";
dtHistorysInfo.Rows.Add(hiArr[
0], hiArr[1], hiArr[2], hiArr[3], hiArr[4], hiArr[5], hiArr[6], hiArr[7]);
for (int k = 0; k < dtAllHistorysInfo.Rows.Count; k++)
{
string actName = dtAllHistorysInfo.Rows[k]["ActName"].ToString();
string approvalPerson = dtAllHistorysInfo.Rows[k]["Emp_Name"].ToString();
string FinalAction = dtAllHistorysInfo.Rows[k]["FinalAction"].ToString();
string approvalDate = dtAllHistorysInfo.Rows[k]["ActivityFinishDate"].ToString();
hiArr[
0] = approvalPerson;
hiArr[
1] = actName;
hiArr[
2] = FinalAction;
hiArr[
3] = approvalDate;
hiArr[
4] = "";
hiArr[
5] = "";
hiArr[
6] = "";
hiArr[
7] = "";
if (k + 1 < dtAllHistorysInfo.Rows.Count)
{
hiArr[
4] = dtAllHistorysInfo.Rows[k + 1]["Emp_Name"].ToString();
hiArr[
5] = dtAllHistorysInfo.Rows[k + 1]["ActName"].ToString();
hiArr[
6] = dtAllHistorysInfo.Rows[k + 1]["FinalAction"].ToString();
hiArr[
7] = dtAllHistorysInfo.Rows[k + 1]["ActivityFinishDate"].ToString();
}
dtHistorysInfo.Rows.Add(hiArr[
0], hiArr[1], hiArr[2], hiArr[3], hiArr[4], hiArr[5], hiArr[6], hiArr[7]);
k
++;
}

}
if (ProcName == "费用报销单")
{
#region 费用报销单打印
#region 数据处理

//将取出来的基本信息转换为想要的格式
System.Data.DataTable dtBasicInfo0 = new System.Data.DataTable();
dtBasicInfo0.Columns.Add(
"1");
dtBasicInfo0.Columns.Add(
"2");
dtBasicInfo0.Columns.Add(
"3");
dtBasicInfo0.Columns.Add(
"4");
if (dtBasicInfo.Rows.Count > 0)
{
for (int j = 0; j < dtBasicInfo.Rows.Count; j++)
{
dtBasicInfo0.Rows.Add(
"申请人", dtBasicInfo.Rows[j]["Applicant"], "部门", dtBasicInfo.Rows[j]["Dept"]);
dtBasicInfo0.Rows.Add(
"工号", dtBasicInfo.Rows[j]["Emp_Code"], "职务/职称", dtBasicInfo.Rows[j]["Post"]);
dtBasicInfo0.Rows.Add(
"电话", dtBasicInfo.Rows[j]["ApplicantTel"], "手机", dtBasicInfo.Rows[j]["Phone"]);
dtBasicInfo0.Rows.Add(
"处长", dtBasicInfo.Rows[j]["Director"], "部长", dtBasicInfo.Rows[j]["Minister"]);
}
}

#endregion
string pictureName = ConfigurationManager.AppSettings["logImg"];
InsertPicture(WordDoc, pictureName,
95, 38);
InsertText(WordDoc,
" 费用报销单", new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false);
InsertPicture(WordDoc, CreateFilePath
+ str, 250, 38);
InsertText(WordDoc,
"", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, true);
InsertText(WordDoc,
"申请人信息", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false);
double[] dtBasicInfoWidthArr = new double[4] { 2.5, 6.77, 2.5, 6.76 };//设置表格的宽度
InsertTable(WordDoc, dtBasicInfo0, true, dtBasicInfoWidthArr,9);

InsertText(WordDoc,
"审批历史记录", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false);

double[] dtBasic = new double[8] { 1.35, 3.36, 1.85, 2.9, 1.35, 3.37, 1.65, 2.9 };//设置表格的宽度
InsertTable(WordDoc, dtHistorysInfo, true, dtBasic, 9);

InsertText(WordDoc,
"注:本借款单适用于除差旅费之外备用金借款以及一次性付款项目的借款", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Regular), Word.WdParagraphAlignment.wdAlignParagraphLeft, true, true);

if (ProcInstIDArrLenth - 1 != i)
{
InsertBreak(WordDoc, Nothing);
}
#endregion
}

}

//生成条形码
private static void CreateBmp(string sn, string CreateFilePath, string guid)
{
HttpWebRequest req
= null;
HttpWebResponse resp
= null;
Stream stream
= null;
ASCIIEncoding encoding
= new ASCIIEncoding();
string webString = ConfigurationManager.AppSettings["webString"];
String postData
= "method=barcode" + "&barcode=" + sn;
byte[] data = encoding.GetBytes(postData);

req
= (HttpWebRequest)WebRequest.Create(webString + "BmpHandler.ashx");
req.Method
= "POST";
req.Timeout
= 5000;
req.ContentType
= "application/x-www-form-urlencoded";
req.ContentLength
= data.Length;
stream
= req.GetRequestStream();
stream.Write(data,
0, data.Length);

resp
= (HttpWebResponse)req.GetResponse();
Stream streamOut
= resp.GetResponseStream();

FileStream fs
= new FileStream(CreateFilePath + guid, FileMode.Create);
//实例化一个StreamWriter-->与fs相关联
BinaryWriter sw = new BinaryWriter(fs);

byte[] bArr = new byte[1024];
int read = 0;
do
{
read
= streamOut.Read(bArr, 0, 1024);
sw.Write(bArr,
0, read);

}
while (read > 0);


//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}

#region - 页面设置 -
public static void SetPage(Word.Application oWord, Word._Document oDoc, string orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
Logger.Log.Info(
"Word.Name" + oWord.Name);
Logger.Log.Info(
"oDoc" + oDoc);
oDoc.PageSetup.PageWidth
= oWord.CentimetersToPoints((float)width);
oDoc.PageSetup.PageHeight
= oWord.CentimetersToPoints((float)height);

if (orientation == "横板")
{
oDoc.PageSetup.Orientation
= Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
}
oDoc.PageSetup.TopMargin
= (float)(topMargin * 25);//上边距
oDoc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左边距
oDoc.PageSetup.RightMargin = (float)(rightMargin * 25);//右边距
oDoc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下边距
}
#endregion

#region - 插入分页符 -
public static void InsertBreak(Word._Document WordDoc, Object Nothing)
{
Word.Paragraph para;
para
= WordDoc.Content.Paragraphs.Add(ref Nothing);
object pBreak = (int)Word.WdBreakType.wdSectionBreakNextPage;
para.Range.InsertBreak(
ref pBreak);
para.Range.Delete();
}
public static void DeleteBreak(Word.Application wordApp, Object Nothing)
{
Word.Range range1, range2;
// 跳转种类
object objWhat = Word.WdGoToItem.wdGoToPage;
// 跳转位置
object objWhich = Word.WdGoToDirection.wdGoToLast;
// 转向最后一页
wordApp.Selection.GoTo(ref objWhat, ref objWhich, ref Nothing, ref Nothing);
// Range取得
range1 = wordApp.Selection.Range;
range2
= wordApp.ActiveDocument.Range(ref Nothing, ref Nothing);
object start = range1.Start;
object end = range2.End;
// 删除最后一页
wordApp.ActiveDocument.Range(ref start, ref end).Delete(ref Nothing, ref Nothing);
}
#endregion

#region - 插入文本 -
public static bool InsertText(Word._Document oDoc, string strText, System.Drawing.Font font, Word.WdParagraphAlignment wdAlign, bool isAftre)
{
try
{
Word.Range rng
= oDoc.Content;

int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;

rng
= oDoc.Range(ref start, ref end);

if (isAftre == true)
{
strText
+= "\r\n";
}

rng.Text
= strText;

rng.Font.Name
= font.Name;
rng.Font.Size
= font.Size;
if (font.Style == System.Drawing.FontStyle.Bold) { rng.Font.Bold = 1; } //设置单元格中字体为粗体
rng.ParagraphFormat.Alignment = wdAlign;//设置文本对齐格式(左对齐,右对齐,居中)
return true;
}
catch (Exception)
{
return false;
}
}
#endregion

#region -插入表格
public static bool InsertTable(Word._Document oDoc, System.Data.DataTable dt, bool haveBorder, double[] colWidths,int size)
{
try
{
object Nothing = System.Reflection.Missing.Value;

int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;

//表格起始坐标
Word.Range tableLocation = oDoc.Range(ref start, ref end);

//添加Word表格
Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing);

if (colWidths != null)
{
for (int i = 0; i < colWidths.Length; i++)
{
table.Columns[i
+ 1].Width = (float)(28.5F * colWidths[i]);
}
}

//设置TABLE的样式
table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;
//table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8"));
table.Range.Font.Size = size;
table.Range.Font.Name
= "Arial";
table.Range.Font.Bold
= 0;
table.Range.ParagraphFormat.Alignment
= Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
table.Range.Cells.VerticalAlignment
= Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

if (haveBorder == true)
{
//设置外框样式
table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
table.Borders.InsideLineStyle
= Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
//样式设置结束
}
//循环store的行和列创建Table
for (int row = 0; row < dt.Rows.Count; row++)
{
for (int col = 0; col < dt.Columns.Count; col++)
{
table.Cell(row
+ 1, col + 1).Range.Text = dt.Rows[row][col].ToString();
var text = table.Cell(row + 1, col + 1).Range.Text;
if (text.Length > 3)
{
if (text.Substring(text.Length - 3) == "\r\r\a")
{

table.Cell(row
+ 1, col + 1).Range.Text = text.Substring(0, text.Length - 3);

}
if (table.Cell(row + 1, 1).Range.Text == "汇率填写备注\r\a")
{
table.Cell(row
+ 1, 2).Merge(table.Cell(row + 1, 5));
}
}

}
}
if (table.Cell(1, 1).Range.Text == "关联预算审批流程\r\a")//判断哪些表格需要合并单元格,先这样子写,这样写不好,以后想办法
{
table.Cell(
1, 2).Merge(table.Cell(1, 3));
table.Cell(
2, 3).Merge(table.Cell(2, 4));
table.Cell(
2, 3).Merge(table.Cell(2, 4));
table.Cell(
3, 3).Merge(table.Cell(3, 4));
table.Cell(
3, 3).Merge(table.Cell(3, 4));
table.Cell(
4, 2).Merge(table.Cell(4, 3));

}
return true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
finally
{

}
}
#endregion

#region - 插入图片 -
public static bool InsertPicture(Word._Document oDoc, string pictureName, float width, float height)
{
try
{
Word.Range rng
= oDoc.Content;

int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;

rng
= oDoc.Range(ref start, ref end);
Object range
= rng;
object LinkToFile = false;
object SaveWithDocument = true;
Word.InlineShape shape
= oDoc.Application.ActiveDocument.InlineShapes.AddPicture(pictureName, ref LinkToFile, ref SaveWithDocument, ref range);//插入图片

shape.Width
= width;
shape.Height
= height;
return true;
}
catch (Exception e)
{

HY.Common.Utils.Logger.Log.Info(
"InsertPicture:" + e.ToString());
return false;
}

}
#endregion

#region - 清除word进程 -
/**/
/// <summary>
/// 清除word进程
/// </summary>
public static void KillWordProcess()
{
System.Diagnostics.Process[] myPs;
myPs
= System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process p in myPs)
{
if (p.Id != 0)
{
string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
try
{
if (p.Modules != null)
if (p.Modules.Count > 0)
{
System.Diagnostics.ProcessModule pm
= p.Modules[0];
myS
+= "/n Modules[0].FileName:" + pm.FileName;
myS
+= "/n Modules[0].ModuleName:" + pm.ModuleName;
myS
+= "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
if (pm.ModuleName.ToLower() == "winword.exe")
p.Kill();
}
}
catch
{ }
finally
{

}
}
}
}
#endregion
}
}