《C#打印word文档Excel文档.doc》由会员分享,可在线阅读,更多相关《C#打印word文档Excel文档.doc(14页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、C#打印word文档,Excel文档本类调用Office的com组件执行对word文档和excel文档的打印。只能支持文件后缀名为.doc,.docx,.xls,.xlsx,.txt。1 添加对office组件的引用系统里必须安装office2003及以上版本。我是安装了office2007.项目节点上点击右键,选择“添加引用”。在COM页面,选中 Microsoft word 12.0 object library 和Microsoft excel 12.0 object library.2003版本显示的是 11.0.项目引用节点下会出现如下2个引用。Microsoft.office.In
2、terop.excel 和 Microsoft.office.Interop.Word.2 打印类using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;using System.IO;using System.Drawing.Printing;using LaisonTech.CommonBLL; /此命名空间里定义了本人写的其他组件.请参见百度文档:通用文件处理方法集合using System.Reflecti
3、on;using Microsoft.Office.Interop.Excel;using Microsoft.Office.Interop.Word;using MSWord = Microsoft.Office.Interop.Word;using MSExcel = Microsoft.Office.Interop.Excel;namespace LaisonTech.CommonBLL#region 辅助定义 /打印机状态 FlagsAttribute internal enum PrinterStatus PRINTER_STATUS_BUSY = 0x, PRINTER_STATU
4、S_DOOR_OPEN = 0x, PRINTER_STATUS_ERROR = 0x, PRINTER_STATUS_INITIALIZING = 0x, PRINTER_STATUS_IO_ACTIVE = 0x, PRINTER_STATUS_MANUAL_FEED = 0x, PRINTER_STATUS_NO_TONER = 0x, PRINTER_STATUS_NOT_AVAILABLE = 0x, PRINTER_STATUS_OFFLINE = 0x, PRINTER_STATUS_OUT_OF_MEMORY = 0x, PRINTER_STATUS_OUTPUT_BIN_FU
5、LL = 0x, PRINTER_STATUS_PAGE_PUNT = 0x, PRINTER_STATUS_PAPER_JAM = 0x, PRINTER_STATUS_PAPER_OUT = 0x, PRINTER_STATUS_PAPER_PROBLEM = 0x, PRINTER_STATUS_PAUSED = 0x, PRINTER_STATUS_PENDING_DELETION = 0x, PRINTER_STATUS_PRINTING = 0x, PRINTER_STATUS_PROCESSING = 0x, PRINTER_STATUS_TONER_LOW = 0x, PRIN
6、TER_STATUS_USER_INTERVENTION = 0x, PRINTER_STATUS_WAITING = 0x, PRINTER_STATUS_WARMING_UP = 0x ; StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto) internal struct structPrinterDefaults MarshalAs(UnmanagedType.LPTStr) public String pDatatype; public IntPtr pDevMode; MarshalAs(UnmanagedType.
7、I4) public int DesiredAccess; ; /Nested Types StructLayout(LayoutKind.Sequential) public class DOCINFOA MarshalAs(UnmanagedType.LPStr) public string pDocName; MarshalAs(UnmanagedType.LPStr) public string pOutputFile; MarshalAs(UnmanagedType.LPStr) public string pDataType; StructLayout(LayoutKind.Seq
8、uential) internal struct PRINTER_INFO_2 public string pServerName; public string pPrinterName; public string pShareName; public string pPortName; public string pDriverName; public string pComment; public string pLocation; public IntPtr pDevMode; public string pSepFile; public string pPrintProcessor;
9、 public string pDatatype; public string pParameters; public IntPtr pSecurityDescriptor; public uint Attributes; public uint Priority; public uint DefaultPriority; public uint StartTime; public uint UntilTime; public uint Status; public uint cJobs; public uint AveragePPM; #endregion / / 打印机状态 / publi
10、c enum ePrinterState UnknownStatus = -1, Ready = 0, Paused = 1, Error = 2, PendingDeletion = 4, PaperJam = 8, NoPaper = 0x10, ManualFeedPaper = 0x20, PaperProblem = 0x40, OffLine = 0x80, Transmitting = 0x100, Busy = 0x200, Printing = 0x400, OutputBinFull = 0x800, NotAvailable = 0x1000, Processing =
11、0x4000, Initializing = 0x8000, / / 热机中 / WarmingUp = 0x10000, / / 墨粉不足 / TonerLow = 0x20000, / / 无墨粉 / NoToner = 0x40000, / / 当前页无法打印 / PagePunt = 0x80000, / / 需要用户干预 / UserIntervention = 0x, OutOfMemory = 0x, DoorIsOpen = 0x, Waiting = 0x, / / 打印的文件类型 / public enum ePrintFileType Invalid = -1, Text
12、File = 0, Word = 1, Excel = 2 / / 打印类 / 使用方法: / GetPrinterList 获取所有可用打印机名称列表 / CheckPrinterValid 检查某个打印机是否可用. / GetPrinterStatus 获取打印机状态 / PrintFile 使用指定打印机打印文件. / PrintFileBySystem 使用指定打印机打印文件,调用操作系统默认程序打印 / public class PrinterHelper #region 对外接口 / / 获取本机安装的所有打印机 / / public static List GetPrinterL
13、ist() List ret = new List(); if (PrinterSettings.InstalledPrinters.Count 1) return ret; foreach (String printername in PrinterSettings.InstalledPrinters) ret.Add(printername); return ret; / / 检查打印机是否可用 / / / public static Boolean CheckPrinterValid(String printername) if (printername.Length 1) return
14、 false; ePrinterState state = GetPrinterStatus(printername); if (state = ePrinterState.Ready | state = ePrinterState.Busy) return true; return false; / / 获取打印机状态 / / / public static ePrinterState GetPrinterStatus(string PrinterName) int intValue = GetPrinterStatusInt(PrinterName); ePrinterState ret
15、= (ePrinterState)intValue; return ret; / / 调用COM接口打印文件。推荐使用。 / / / / public static Boolean PrintFile(String printername, String filename) Boolean bl = FileProcessor.FileExist(filename); if (!bl) return false; ePrintFileType filetype = GetFileType(filename); /判断是否为 txt 或word 或 Excel. /如果都不是,禁止打印 if (
16、filetype = ePrintFileType.Invalid) return false; /先保存默认的打印机 /默认打印机 不是 指定打印机,需要修改默认打印机 String defaultPrinter = GetDefaultPrinter(); Boolean needchangeprinter = !(defaultPrinter.Equals(printername, StringComparison.OrdinalIgnoreCase); /将指定的打印机设为默认打印机 if (needchangeprinter) bl = SetDefaultPrinter(print
17、ername); bl = false; if (filetype = ePrintFileType.Excel) bl = PrintExcel(printername, filename); else bl = PrintWord_Text(printername, filename); /将默认打印机还原 if (needchangeprinter) SetDefaultPrinter(defaultPrinter); return bl; #endregion#region 内部实现 private static List m_SuffixNameList = new List txt
18、, doc, docx, xls, xlsx,csv; / / 根据文件后缀名获取文件类型 / / / private static ePrintFileType GetFileType(String filename) String sfxname = FileProcessor.GetFileSuffixName(filename); sfxname = sfxname.ToLower(); Int32 idx = m_SuffixNameList.IndexOf(sfxname); if (idx 0) return ePrintFileType.Invalid; if (idx = 0
19、) return ePrintFileType.TextFile; if (idx 3) return ePrintFileType.Word; return ePrintFileType.Excel; / / 打印word,Text / / / / private static Boolean PrintWord_Text(String printername, String filename) object oMissing = Missing.Value; /定义WORD Application相关 MSWord._Application appWord = new MSWord.App
20、lication(); /WORD程序不可见 appWord.Visible = false; /不弹出警告框 appWord.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone; object oTrue = true; object oFalse = false; /打开要打印的文件 object wordFile = filename; MSWord._Document doc = appWord.Documents.Open( ref wordFile, ref oMissing, ref oTrue, ref oFalse, ref oM
21、issing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); /设置指定的打印机 /appWord.ActivePrinter = printername; /true后台打印,false前台打印。 /必须false,否则后台打印时,尚未打印,就调用了后续的Close,造成打印任务无法执行 object printbackgroud
22、= false; doc.PrintOut(ref printbackgroud, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); object doNotSaveChan
23、ges = MSWord.WdSaveOptions.wdDoNotSaveChanges; /打印完关闭WORD文件 doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing); /退出WORD程序 appWord.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing); doc = null; appWord = null; return true; / / 打印Excel文件 / / / / private static Boolean PrintExcel(String p
24、rintername, String filename) object oMissing = Missing.Value; /定义WORD Application相关 MSExcel._Application appxls = new MSExcel.Application(); /WORD程序不可见 appxls.Visible = false; /不弹出警告框 appxls.DisplayAlerts = false; object oTrue = true; object oFalse = false; /打开要打印的文件 MSExcel._Workbook book = appxls.
25、Workbooks.Open(filename); /Excel 规定,首个表格的下标为1 MSExcel._Worksheet sheet = (MSExcel._Worksheet)book.Worksheets1; sheet.Activate(); sheet.PageSetup.PrintGridlines = true; sheet.PrintOut(); /for (Int32 sheetidx = 1; sheetidx = book.Worksheets.Count; +sheetidx) / / sheet = (MSExcel._Worksheet)book.Worksh
26、eetssheetidx; / if (sheet = null) / / break; / / sheet.PrintOut(); / sheet = null; book.Saved = false; object saved = false; book.Close(saved); appxls.Quit(); book = null; appxls = null; /操作过Excel对象后,必须强制垃圾回收.否则无法退出Exccel进程 CommonCompute.GCCollect(); return true; #endregion#region 获取设置默认打印机 / / 设置默认
27、打印机 / / / DllImport(Winspool.drv, CharSet = CharSet.Auto, SetLastError = true) public static extern bool SetDefaultPrinter(string printerName); DllImport(winspool.drv, CharSet = CharSet.Auto, SetLastError = true) private static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int pcchBuffe
28、r); / / 获取默认打印机 / / public static String GetDefaultPrinter() StringBuilder strbuilder = new StringBuilder(2048); Int32 buflen = strbuilder.Capacity; GetDefaultPrinter(strbuilder, ref buflen); String ret = strbuilder.ToString(); return ret; #endregion#region 系统API / Methods DllImport(winspool.Drv, Ca
29、llingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true) internal static extern bool ClosePrinter(IntPtr hPrinter); DllImport(winspool.Drv, CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true) internal static extern bool EndDocPrinter(IntPtr hPrinter); DllImport(winspoo