您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關C#中怎么將Excel轉成PDF,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Excel; //Office 命名空間 namespace OfficeToPdf { //excel 類 class ExcelConverter { //構造函數 public ExcelConverter() { } /// <summary> /// 轉換excel 成PDF文檔 /// </summary> /// <param name="_lstrInputFile">原文件路徑</param> /// <param name="_lstrOutFile">pdf文件輸出路徑</param> /// <returns>true 成功</returns> public bool ConverterToPdf(string _lstrInputFile,string _lstrOutFile) { Microsoft.Office.Interop.Excel.Application lobjExcelApp = null; Microsoft.Office.Interop.Excel.Workbooks lobjExcelWorkBooks = null; Microsoft.Office.Interop.Excel.Workbook lobjExcelWorkBook = null; string lstrTemp = string.Empty; object lobjMissing = System.Reflection.Missing.Value; try { lobjExcelApp = new Microsoft.Office.Interop.Excel.Application(); lobjExcelApp.Visible = true; lobjExcelWorkBooks = lobjExcelApp.Workbooks; lobjExcelWorkBook = lobjExcelWorkBooks.Open(_lstrInputFile, true, true, lobjMissing, lobjMissing, lobjMissing, true, lobjMissing, lobjMissing, lobjMissing, lobjMissing, lobjMissing, false, lobjMissing, lobjMissing); //Microsoft.Office.Interop.Excel 12.0.0.0之后才有這函數 lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls" + (lobjExcelWorkBook.HasVBProject ? 'm' : 'x'); //lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls"; lobjExcelWorkBook.SaveAs(lstrTemp, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel4Workbook, Type.Missing, Type.Missing, Type.Missing, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing); //輸出為PDF 第一個選項指定轉出為PDF,還可以指定為XPS格式 lobjExcelWorkBook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, _lstrOutFile, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, Type.Missing, false, Type.Missing, Type.Missing, false, Type.Missing); lobjExcelWorkBooks.Close(); lobjExcelApp.Quit(); } catch (Exception ex) { //其他日志操作; return false; } finally { if (lobjExcelWorkBook != null) { lobjExcelWorkBook.Close(Type.Missing,Type.Missing,Type.Missing); Marshal.ReleaseComObject(lobjExcelWorkBook); lobjExcelWorkBook = null; } if(lobjExcelWorkBooks != null) { lobjExcelWorkBooks.Close(); Marshal.ReleaseComObject(lobjExcelWorkBooks); lobjExcelWorkBooks = null; } if(lobjExcelApp != null) { lobjExcelApp.Quit(); Marshal.ReleaseComObject(lobjExcelApp); lobjExcelApp = null; } //主動激活垃圾回收器,主要是避免超大批量轉文檔時,內存占用過多,而垃圾回收器并不是時刻都在運行! GC.Collect(); GC.WaitForPendingFinalizers(); } return true; } } }
關于C#中怎么將Excel轉成PDF就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。