[英]convert excel spreadsheet to PDF Interop.Excel alternative in C#
(C#)正在使用Microsoft.Office.Interop.Excel保存為PDF文件。
但是對於大多數Excel文件(非常復雜的文件,其中某些文件大小為35Mb,其他文件帶有宏...),該解決方案無法正常工作
我希望將Excel文件轉換為PDF格式。
除了Interop.Excel之外,還有其他免費解決方案嗎?
您檢查過此鏈接了嗎? http://www.codeproject.com/Articles/17574/Programmatically-Convert-Documents-to-PDFs-the-Eas
已編輯
首先,您必須下載並安裝Ghostscript。 通過添加本地打印機繼續,然后取消選中“自動檢測並安裝即插即用打印機”。
創建一個新的本地端口,然后輸入“ C:\\ output.ps”作為端口名稱。
為了使GhostScript正確解析PostScript,必須將其設置為打印機驅動程序。 您可以在lib文件夾中的GhostScript安裝目錄中找到GhostScript的打印機驅動程序。
為了使所附的代碼起作用,將打印機命名為Ghostscript。 附帶的應用程序將所有難題擺放到位。 首先,應用程序存儲當前的默認打印機。 稍后將使用它來重新設置打印機。
public static string GetDefaultPrinterName(){
PrintDocument pd = new PrintDocument();
return pd.PrinterSettings.PrinterName;
}
其次,我們之前設置的Ghostscript打印機被設置為默認打印機,因此用戶不必選擇打印機。
public static long SetDefaultPrinterName(string name){
return SetDefaultPrinter(name);
}
第三,我們在文件上調用print命令。 對我來說,這里的技巧是檢測何時打印Excel文件。 我主要處理Excel文檔,需要一種快速的方法來打印整個工作簿,而不僅僅是打印打開的工作表。
public static void CreatePdf(string action, string file, string directory){
if (file.EndsWith("xls")){
Excel.ApplicationClass excel = new Excel.ApplicationClass();
excel.Visible = false;
Excel.Workbook workbook = excel.Workbooks.Open(Path.Combine(directory, file),
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
workbook.PrintOut(Type.Missing, Type.Missing, 1, false, Type.Missing,
false, Type.Missing, Type.Missing);
excel.Quit();
}else{
Process p = new Process();
p.StartInfo.FileName = file;
p.StartInfo.Verb = action;
p.StartInfo.WorkingDirectory = directory;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
Console.WriteLine("Starting process");
p.Start();
//p.Kill();
}
Console.WriteLine("Creating Pdf");
CreatePdf(file);
}
最后,我們調用GhostScript可執行文件,為其提供要輸出到的文件名以及在何處查找PostScript。 為了將可執行文件傳遞給語句,我們只需將輸入重定向到我們創建的命令,然后獲取輸出。
private static string CreatePdf(string fileName){
string command = "gswin32c -q -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=\"" +
fileName + ".pdf\" -fc:\\output.ps";
Console.WriteLine(command);
Process p = new Process();
StreamWriter sw;
StreamReader sr;
ProcessStartInfo info = new ProcessStartInfo("cmd");
info.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
Console.WriteLine("Current directory: " + info.WorkingDirectory);
info.CreateNoWindow = true;
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
p.StartInfo = info;
p.Start();
sw = p.StandardInput;
sr = p.StandardOutput;
sw.AutoFlush = true;
sw.WriteLine(command);
sw.Close();
string ret = sr.ReadToEnd();
Console.WriteLine(ret);
return ret;
}
在GhostScript運行之后,我們只需將打印機設置回先前的默認值,而用戶則是最明智的選擇。
try{
Printers.SetDefaultPrinterName(currentPrinterName);
}catch{}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.