private bool ExcelToPDF(string sourcePath, string targetPath) { bool result; object missing = Type.Missing; Excel.ApplicationClass application = null; Excel.Workbook workBook = null; try { application = new Excel.ApplicationClass(); object target = targetPath; object type = Excel.XlFixedFormatType.xlTypePDF; workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); workBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); result = true; } catch { result = false; } finally { workBook.Close(true, missing, missing); application.Quit(); } return(result); }
/// <summary> /// Excel 转成 pdf 文件 /// </summary> /// <returns>错误信息,null 代表正常</returns> override protected string ExcelToPDF() { string result = null; var application = new excel.Application(); excel.Workbook document = null; try { application.Visible = false; document = application.Workbooks.Open(base._officeFileName); document.ExportAsFixedFormat(excel.XlFixedFormatType.xlTypePDF, base._pdfFileName); document.Save(); } catch (Exception e) { result = e.Message; } finally { document.Close(); uint processID; GetWindowThreadProcessId((IntPtr)application.Application.Hwnd, out processID); System.Diagnostics.Process.GetProcessById((int)processID).Kill(); } return(result); }
/// <summary> /// 文档另存为PDF /// </summary> /// <param name="fileName"></param> /// <returns></returns> public void SaveAsPDF(string fileName) { try { ////Temp Excel File //string tmpExcel = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls" + (_wb.HasVBProject ? 'm' : 'x'); //SaveAsExcel(tmpExcel); _wb.ExportAsFixedFormat( Type: Excel.XlFixedFormatType.xlTypePDF , Filename: fileName , Quality: Excel.XlFixedFormatQuality.xlQualityStandard , IncludeDocProperties: true , IgnorePrintAreas: false , From: Type.Missing , To: Type.Missing , OpenAfterPublish: Type.Missing , FixedFormatExtClassPtr: Type.Missing ); } catch (Exception ex) { throw ex; } }
/// <summary> /// PDFファイルに保存 /// </summary> /// <param name="FileName"></param> public void SaveAsPDF(string FileName) { try { Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF; m_objBook.ExportAsFixedFormat(targetType, FileName, Excel.XlFixedFormatQuality.xlQualityStandard, true, true, miss, miss, false, miss); } catch { try { m_objBook.Close(false, miss, miss); } catch { } try { m_objExcel.Quit(); } catch { } } }
public async Task <dynamic> GetExcel(dynamic opts) { string file = Path.GetFullPath(opts.input as string); string pdfFile = Path.GetFullPath(opts.output as string); return(await this.scheduler.StartNew(() => { Thread.Sleep(100); CreateExcel(); Excel.Workbook book = this.msexcel.Workbooks.Open(file, 2, true, Type.Missing, Type.Missing, Type.Missing, false, Type.Missing, Type.Missing, false, false, Type.Missing, false, true, Excel.XlCorruptLoad.xlNormalLoad); Delay(0); try { Delay(1); book.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFile, Excel.XlFixedFormatQuality.xlQualityStandard, true, false); Delay(2); } finally { (book as Excel._Workbook).Close(false); Marshal.ReleaseComObject(book); } //closeInternal(); return pdfFile; })); }
public static void ConvertExcelDocumentToPdf(string srcFile, string dstFile) { Excel.Application excelApp = null; Excel.Workbook excelWorkBook = null; try { excelApp = new Excel.Application(); excelWorkBook = excelApp.Workbooks.Open( srcFile, ReadOnly: true, IgnoreReadOnlyRecommended: true, Notify: false ); excelWorkBook.ExportAsFixedFormat( Type: Excel.XlFixedFormatType.xlTypePDF, Filename: dstFile, Quality: Excel.XlFixedFormatQuality.xlQualityStandard, IncludeDocProperties: true, OpenAfterPublish: false, IgnorePrintAreas: true ); } finally { excelWorkBook?.Close(SaveChanges: false); excelApp?.Quit(); } }
private void SaveWorkBook(Excel.Workbook wb, string filename) { string extension = System.IO.Path.GetExtension(filename); if (extension.Equals(".xlsx")) { wb.SaveAs(filename, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlShared, Excel.XlSaveConflictResolution.xlLocalSessionChanges, missing, missing, missing, missing); } else if (extension.Equals(".pdf")) { string paramExportFilePath = filename; Excel.XlFixedFormatType paramExportFormat = Excel.XlFixedFormatType.xlTypePDF; Excel.XlFixedFormatQuality paramExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard; bool paramOpenAfterPublish = false; bool paramIncludeDocProps = true; bool paramIgnorePrintAreas = true; object paramFromPage = Type.Missing; object paramToPage = Type.Missing; // Save it in the target format. wb.ExportAsFixedFormat(paramExportFormat, paramExportFilePath, paramExportQuality, paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage, paramToPage, paramOpenAfterPublish, missing); } }
/// <summary> /// Saves the document out with the appropriate new filename and format. /// Also does any special handling such as accepting/rejecting changes /// before saving. /// </summary> private void SaveDocument() { HandleTrackedChanges(); object missing = System.Reflection.Missing.Value; object newFileName = m_newFileName; Excel_Class.XlSaveAsAccessMode accessMode = Excel_Class.XlSaveAsAccessMode.xlNoChange; object conflictResolution = Excel_Class.XlSaveConflictResolution.xlOtherSessionChanges; if (m_newFormatType.Equals(Excel_Class.XlFixedFormatType.xlTypePDF)) { m_workbook.ExportAsFixedFormat(Excel_Class.XlFixedFormatType.xlTypePDF, m_newFileName, missing, missing, missing, missing, missing, missing, missing); } else { m_workbook.SaveAs(m_newFileName, m_newFormatType, missing, missing, missing, missing, accessMode, conflictResolution, missing, missing, missing, missing); } object saveChanges = false; object routeWb = false; m_workbook.Close(saveChanges, missing, routeWb); m_workbook = null; }
private void Generate_PDFs() { Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); object misValue = System.Reflection.Missing.Value; Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue); Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlWorkSheet.Cells[1, 1] = "AppNo"; xlWorkSheet.Cells[1, 2] = "Name"; xlWorkSheet.Cells[1, 3] = "Department"; xlWorkSheet.Cells[1, 4] = "Category"; xlWorkSheet.Cells[1, 5] = "Aggregate"; studentsSelectedList = studentsSelectedList.OrderByDescending(o => o.aggregate).ToList(); for (int i = 0; i < studentsSelectedList.Count(); i++) { //Setting width of the Excel Coloumns. var studentinfo = studentsSelectedList[i]; xlWorkSheet.Columns[2].ColumnWidth = 18; xlWorkSheet.Columns[3].ColumnWidth = 21; xlWorkSheet.Columns[4].ColumnWidth = 18; xlWorkSheet.Columns[5].ColumnWidth = 18; //Setting information in Excel Workbook xlWorkSheet.Cells[i + 2, 1] = studentinfo.appRefNum; xlWorkSheet.Cells[i + 2, 2] = studentinfo.name; xlWorkSheet.Cells[i + 2, 3] = studentinfo.preferenceList[0]; xlWorkSheet.Cells[i + 2, 4] = studentinfo.category; xlWorkSheet.Cells[i + 2, 5] = studentinfo.aggregate; } //Saving as PDF xlWorkBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, "C:\\Users\\hassa\\Desktop\\MeritListGenerator\\MeritListGenerator\\MeritList.pdf"); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); }
public static void TestToPDF() { string strFileName = @"D:/BaiduNetdiskDownload/#137959/20180125_1つの具体例を作る/03_XXX_ABC株式会社(レポート).xls"; Action <Excel.Application, Excel.Workbook> action = (Excel.Application app, Excel.Workbook wb) => { //wb.Worksheets.Select();//导出全部sheet //wb.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, // @"D:/BaiduNetdiskDownload/#137959/20180125_1つの具体例を作る/20180227_01.pdf", // Excel.XlFixedFormatQuality.xlQualityStandard); Excel.Workbook tmpWb = app.Workbooks.Add(); for (int i = 3; i <= 25; i++) { Excel.Worksheet copysheet = (Excel.Worksheet)wb.Sheets[i]; copysheet.Copy(tmpWb.Worksheets[tmpWb.Worksheets.Count]); } Excel.Worksheet lastsheet = (Excel.Worksheet)tmpWb.Worksheets[tmpWb.Worksheets.Count]; Log.Println("最后一个sheet名: " + lastsheet.Name); if (lastsheet.Name.Equals("Sheet1")) { lastsheet.Delete(); //删除最后一个名字是Sheet1的sheet } tmpWb.Worksheets.Select(); tmpWb.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, @"D:/BaiduNetdiskDownload/#137959/20180125_1つの具体例を作る/20180227_01.pdf", Excel.XlFixedFormatQuality.xlQualityStandard); Log.Println("PDF文件导出成功。"); //tmpWb.SaveAs(@"D:/BaiduNetdiskDownload/#137959/20180125_1つの具体例を作る/tmp20180227_01.xls"); //tmpWb.Close(); tmpWb.Close(false, Type.Missing, Type.Missing); }; ExcelUtil.GetExcelWorkbook(strFileName, action); }
public static void convert(string originalFile, string outPutFile) { Excel.Workbook excelWorkbook = null; object unknownType = Type.Missing; var excelApp = new Excel.Application(); //excelApp.Visible = false; excelApp.Visible = false; excelApp.DisplayAlerts = false; excelWorkbook = excelApp.Workbooks.Open(originalFile, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType); excelWorkbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, outPutFile, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType, unknownType); excelApp.Quit(); return; }
public static void ConvertFromExcel(string sourcePath, string targetPath) { Excel.Application excelApplication = null; Excel.Workbook excelWorkbook = null; try { excelApplication = new Excel.Application(); excelWorkbook = excelApplication.Workbooks.Open(sourcePath); excelWorkbook.ExportAsFixedFormat( Excel.XlFixedFormatType.xlTypePDF, targetPath, Excel.XlFixedFormatQuality.xlQualityStandard, true, true, OpenAfterPublish: false ); } finally { if (excelWorkbook != null) { excelWorkbook.Close(); excelWorkbook = null; } if (excelApplication != null) { excelApplication.Quit(); excelApplication = null; } } }
/// <summary> /// 打印workbook,使用另存为功能转pdf,指定打印页码 /// </summary> /// <param name="workBook">工作簿对象</param> /// <param name="toPath">输出路径</param> /// <param name="pageFrom">打印起始页码</param> /// <param name="pageTo">打印结束页码</param> /// <returns>成功或失败</returns> public static bool SaveExcelWorkbookAsPDFWithPage(EXCEL.Workbook workBook, string toPath, int pageFrom, int pageTo) { bool flag = false; object missing = Type.Missing; try { if (toPath.Length == 0) { flag = false; throw new Exception("需要转换的目标文件路径不能为空。"); } //按照设置好的打印区域发布为pdf workBook.ExportAsFixedFormat( EXCEL.XlFixedFormatType.xlTypePDF, toPath, EXCEL.XlFixedFormatQuality.xlQualityStandard, //可设置为 xlQualityStandard 或 xlQualityMinimum。 true, //包含文档属性 false, //如果设置为 True,则忽略在发布时设置的任何打印区域。如果设置为 False,则使用在发布时设置的打印区域。 pageFrom, //发布的起始页码。如果省略此参数,则从起始位置开始发布。 pageTo, //发布的终止页码。如果省略此参数,则发布至最后一页。 false, //是否发布文件后在查看器中显示文件。 Type.Missing); //再还原为普通视图 flag = true; } catch (Exception exception) { classLims_NPOI.WriteLog(exception, ""); flag = false; } return(flag); }
public static new Boolean Convert(String inputFile, String outputFile) { Microsoft.Office.Interop.Excel.Application app; String tmpFile = null; object oMissing = System.Reflection.Missing.Value; try { app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = true; Microsoft.Office.Interop.Excel.Workbooks workbooks = null; Microsoft.Office.Interop.Excel.Workbook workbook = null; workbooks = app.Workbooks; workbook = workbooks.Open(inputFile, true, true, oMissing, oMissing, oMissing, true, oMissing, oMissing, oMissing, oMissing, oMissing, false, oMissing, oMissing); // Try and avoid xls files raising a dialog tmpFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls" + (workbook.HasVBProject ? "m" : "x"); workbook.SaveAs(tmpFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing); workbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputFile, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, Type.Missing, false, Type.Missing, Type.Missing, false, Type.Missing); workbooks.Close(); app.Quit(); return(true); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } finally { if (tmpFile != null) { System.IO.File.Delete(tmpFile); } app = null; } }
void ExportXPS(Microsoft.Office.Interop.Excel.Workbook excelWorkbook) { xpsFileName = (new DirectoryInfo(path)).FullName; xpsFileName = xpsFileName.Replace(new FileInfo(path).Extension, "") + ".xps"; excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypeXPS, Filename: xpsFileName, OpenAfterPublish: false); }
public byte[] ConvertToPDF(byte[] data, string extention) { var dataDosya = @"C:\Document"; var pdfDosya = @"C:\PDF"; Random rnd = new Random(); int randomSayi = rnd.Next(111111); string dosyaPathdata = dataDosya + @"\" + randomSayi + "." + extention; string dosyapathPdf = pdfDosya + @"\" + randomSayi + ".pdf"; File.WriteAllBytes(dosyaPathdata, data); if (extention == "xlsx") { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = false; Microsoft.Office.Interop.Excel.Workbook wkb = app.Workbooks.Open(dosyaPathdata, ReadOnly: true); wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, dosyapathPdf); wkb.Close(); app.Quit(); } else if (extention == "doc" || extention == "docx") { Microsoft.Office.Interop.Word.Application wApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wordDoc = null; object inputFileTemp = dosyaPathdata; wordDoc = wApp.Documents.Open(dosyaPathdata); wordDoc.ExportAsFixedFormat(dosyapathPdf, WdExportFormat.wdExportFormatPDF); wordDoc.Close(); wApp.Quit(); } var pdfByte = File.ReadAllBytes(pdfDosya + @"\" + randomSayi + ".pdf"); if (File.Exists(dosyaPathdata)) { try { File.Delete(dosyaPathdata); } catch (Exception) { throw; } } //if (File.Exists(dosyapathPdf)) //{ // try // { // File.Delete(dosyapathPdf); // } // catch (Exception) // { // throw; // } //} return(pdfByte); }
public void ConvertXlsxToPdf(Excel.Workbook CurrentExcelWorkBook) { GetDefaultPdfName(CurrentExcelWorkBook.Path, CurrentExcelWorkBook.Name); if (_saveDialog.ShowDialog() == DialogResult.OK) { _saveAsPdfPath = _saveDialog.FileName; CurrentExcelWorkBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, _saveAsPdfPath); } }
public static void ConvertFromExcel(string sourcePath, string targetPath) { Excel.Application excelApplication = null; Excel.Workbook excelWorkbook = null; try { excelApplication = new Excel.Application(); excelWorkbook = excelApplication.Workbooks.Open(sourcePath); excelWorkbook.ExportAsFixedFormat( Excel.XlFixedFormatType.xlTypeXPS, targetPath, Excel.XlFixedFormatQuality.xlQualityStandard, true, true, OpenAfterPublish: false ); } finally { if (excelWorkbook != null) { excelWorkbook.Close(); excelWorkbook = null; } if (excelApplication != null) { excelApplication.Quit(); excelApplication = null; } } //Excel.Application application = null; //Excel.Workbook workBook=null; //try //{ // application = new Excel.Application(); // application.Visible = false; // workBook = application.Workbooks.Open(sourcePath); // workBook.PrintOut(1, Type.Missing, 1, false, "Microsoft XPS Document Writer", true, false, targetPath); //} //finally //{ // if (workBook != null) // { // workBook.Close(); // workBook = null; // } // if (application != null) // { // application.Quit(); // application = null; // } //} }
/// <summary> /// 把Excel文件转换成PDF格式文件 /// </summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true=转换成功</returns> public bool XLSConvertToPDF(string sourcePath, string targetPath) { bool result = false; Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF; object missing = Type.Missing; Excel.ApplicationClass application = null; Excel.Workbook workBook = null; try { application = new Excel.ApplicationClass(); object target = targetPath; object type = targetType; workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); result = true; } catch { result = false; } finally { if (workBook != null) { workBook.Close(true, missing, missing); workBook = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } if (workBook != null) { workBook.Close(); } if (application != null) { application.Quit(); } return(result); }
bool XLSConvertToPDF(string sourceFile) { string sourcePath = sourceFile; string targetPath = GetFileName(sourceFile); bool result = false; Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;// Excel.XlFixedFormatType.xlTypePDF; object paramMissing = Type.Missing; Excel.ApplicationClass application = null; Excel.Workbook excelWorkBook = null; try { application = new Excel.ApplicationClass(); object target = targetPath; object type = targetType; excelWorkBook = application.Workbooks.Open(sourcePath); Excel.Worksheet xlSheet = (Excel.Worksheet)excelWorkBook.Worksheets[1]; if (excelWorkBook != null) { excelWorkBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, true, paramMissing, paramMissing, false, paramMissing); result = true; } } catch { result = false; } finally { if (excelWorkBook != null) { excelWorkBook.Close(false, paramMissing, paramMissing); excelWorkBook = null; } if (application != null) { application.Quit(); application = null; } //ms solution is like this GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
private static bool ConvertExcelToPdf(string sourcePath, string targetPath, bool land) { bool result; object missing = Type.Missing; EXCEL.XlFixedFormatType targetType = EXCEL.XlFixedFormatType.xlTypePDF; EXCEL.Application application = null; EXCEL.Workbook workBook = null; try { application = new EXCEL.Application(); application.Visible = false; application.DisplayAlerts = false; string target = sourcePath.Replace(".xlsx", ".pdf"); object type = targetType; workBook = application.Workbooks.Open(sourcePath, AddToMru: false, ReadOnly: true, Password: "******"); foreach (EXCEL.Worksheet sheet in workBook.Sheets) { sheet.PageSetup.Orientation = land ? EXCEL.XlPageOrientation.xlLandscape : EXCEL.XlPageOrientation.xlPortrait; } workBook.ExportAsFixedFormat(targetType, targetPath, EXCEL.XlFixedFormatQuality.xlQualityStandard, IncludeDocProperties: true, IgnorePrintAreas: false); result = true; } catch { result = false; } finally { if (workBook != null) { workBook.Close(SaveChanges: false); workBook = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
/// <summary> /// 将excel文档转换成PDF格式 /// </summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns></returns> private bool ExcelConvertPDF(string sourcePath, string targetPath) { bool result; Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF; //PDF格式 object missing = Type.Missing; Microsoft.Office.Interop.Excel.ApplicationClass application = null; Microsoft.Office.Interop.Excel.Workbook workBook = null; try { application = new Microsoft.Office.Interop.Excel.ApplicationClass(); object target = targetPath; object type = targetType; workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); if (workBook != null) { workBook.ExportAsFixedFormat(targetType, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); result = true; } else { result = false; } } catch (Exception ex) { Response.Write("<p>Excel转PDF出现问题,详情:" + ex.ToString() + "</p>"); result = false; } finally { if (workBook != null) { workBook.Close(true, missing, missing); workBook = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
// private Excel.Worksheet sheet; public override void Convert(String inputFile, String outputFile) { Object nothing = Type.Missing; try { if (!File.Exists(inputFile)) { throw new ConvertException("File not Exists"); } if (IsPasswordProtected(inputFile)) { throw new ConvertException("Password Exist"); } app = new Excel.Application(); books = app.Workbooks; book = books.Open(inputFile, false, true, nothing, nothing, nothing, true, nothing, nothing, false, false, nothing, false, nothing, false); bool hasContent = false; foreach (Excel.Worksheet sheet in book.Worksheets) { Excel.Range range = sheet.UsedRange; if (range != null) { Excel.Range found = range.Cells.Find("*", nothing, nothing, nothing, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, nothing, nothing, nothing); if (found != null) { hasContent = true; } releaseCOMObject(found); releaseCOMObject(range); } } if (!hasContent) { throw new ConvertException("No Content"); } book.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputFile, Excel.XlFixedFormatQuality.xlQualityMinimum, false, false, nothing, nothing, false, nothing); } catch (Exception e) { release(); throw new ConvertException(e.Message); } release(); }
/// <summary> /// Сохраняем файлы в формате пдф и ексель в папки /// </summary> public void MakeExcelFile(decimal moneyAtStart, decimal moneyBalance) { string dateFile; //Повна назва файлу для зберігання try { CreateFolderForSavingFile(excelFilePath, out dateFile); oApp = new Excel.Application(); oBook = oApp.Workbooks.Add(); oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1); // Заповнюємо excel файл данними CreateFullFile(); InputInformationFields(moneyAtStart, moneyBalance); // Зберігаємо файл в форматі екселя oBook.SaveAs(dateFile + ".xlsx"); CreateFolderForSavingFile(pdfFilePath, out dateFile); // Додаткова перевірка при зберіганні pdf файла на встановлене розширення в Office try { oBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, dateFile + ".pdf"); } catch (ArgumentException) { MessageBox.Show("Помилка при збереженні PDF файла. Перевірте чи у Вас встановлене розширення в " + " Microsoft Office для збереження файлів в форматі PDF/XPS.", "Помилка при збереженні PDF", MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (Exception) { MessageBox.Show("Помилка при збереженні pdf файла."); } MessageBox.Show("Дані збережено!", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); } finally { oBook.Close(); oApp.Quit(); } }
public void Parse(object src, object dest) { if (src == null || string.IsNullOrEmpty(src.ToString())) { throw new ArgumentNullException("源文件不能为空"); } if (dest == null || string.IsNullOrEmpty(dest.ToString())) { throw new ArgumentNullException("目标路径不能为空"); } try { xlsx = excelApp.Workbooks.Open(src.ToString(), missing, missing, missing, missing, missing , missing, missing, missing, missing, missing, missing, missing, missing, missing); int startPage = 0; int endPage = 10; if (xlsx != null) { xlsx.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, dest, missing, missing, missing, missing, missing, missing, missing); } } catch (Exception ex) { throw ex; } finally { if (xlsx != null) { xlsx.Close(false, missing, missing); xlsx = null; } if (excelApp != null) { excelApp.Quit(); excelApp = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
/// <summary> /// Excel转PDF /// </summary> /// <param name="excelPath"></param> /// <param name="pdfPath"></param> public static bool ExcelConvertToPDF(string excelPath, string pdfPath, int FromIndex, int ToIndex) { excelPath = CommonUtils.GetPhysicsPath(excelPath); pdfPath = CommonUtils.GetPhysicsPath(pdfPath); bool result = false; XlFixedFormatType targetType = XlFixedFormatType.xlTypePDF; object missing = Type.Missing; Application application = null; Microsoft.Office.Interop.Excel.Workbook workBook = null; try { application = new Application(); object type = targetType; workBook = application.Workbooks.Open(excelPath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); object From = FromIndex == -1 ? missing : FromIndex + 1; object To = ToIndex == -1 ? missing : ToIndex + 1; workBook.ExportAsFixedFormat(targetType, pdfPath, XlFixedFormatQuality.xlQualityStandard, false, false, From, To, missing, missing); result = true; } catch (Exception ex) { result = false; throw ex; } finally { if (workBook != null) { workBook.Close(false, missing, missing); workBook = null; } if (workBook != null) { workBook.Close(false, missing, missing); workBook = null; } if (application != null) { application.Quit(); application = null; } } return(result); }
/// <summary> /// 把Excel文件转换成PDF格式文件 /// </summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true=转换成功</returns> private Boolean XLSConvertToPDF(String sourcePath, String targetPath) { Boolean result = false; OExcel.XlFixedFormatType targetType = OExcel.XlFixedFormatType.xlTypePDF; object missing = Type.Missing; OExcel.ApplicationClass application = null; OExcel.Workbook workBook = null; try { application = new OExcel.ApplicationClass(); object target = targetPath; object type = targetType; workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); if (workBook.IsNullOrEmpty()) { throw new System.ArgumentException("未能实例化"); } workBook.ExportAsFixedFormat(targetType, target, OExcel.XlFixedFormatQuality.xlQualityMinimum, true, true, missing, missing, false, missing); result = true; } catch (Exception) { result = false; throw; } finally { if (workBook != null) { workBook.Close(true, missing, missing); workBook = null; } GC.Collect(); GC.WaitForPendingFinalizers(); if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
public void Parse(object src, object dest) { if (src == null || string.IsNullOrEmpty(src.ToString())) { throw new ArgumentNullException("源文件不能为空"); } if (dest == null || string.IsNullOrEmpty(dest.ToString())) { throw new ArgumentNullException("目标路径不能为空"); } try { xlsx = excelApp.Workbooks.Open(src.ToString(), missing, missing, missing, missing, missing , missing, missing, missing, missing, missing, missing, missing, missing, missing); int startPage = 0; int endPage = 10; if (xlsx != null) { xlsx.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, dest, missing, missing, missing, missing, missing, missing, missing); } } catch (Exception ex) { throw ex; } finally { if (xlsx != null) { xlsx.Close(false, missing, missing); xlsx = null; } if (excelApp!= null) { excelApp.Quit(); excelApp = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
/// <summary> /// 将EXCEL文档转换成PDF格式 /// </summary> /// <param name="_lstrInputFile"></param> /// <param name="_lstrOutFile"></param> /// <returns></returns> public static bool ConvertExcelToPdf(string _lstrInputFile, string _lstrOutFile) { Excel.XlFixedFormatType parameter = Excel.XlFixedFormatType.xlTypePDF; bool result; object missing = Type.Missing; Microsoft.Office.Interop.Excel.ApplicationClass application = null; Excel.Workbook workBook = null; try { application = new Microsoft.Office.Interop.Excel.ApplicationClass(); object target = _lstrOutFile; object type = parameter; workBook = application.Workbooks.Open(_lstrInputFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); workBook.ExportAsFixedFormat(parameter, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); result = true; } catch (Exception ex) { result = false; throw new Exception(ex.Message, ex); } finally { if (workBook != null) { workBook.Close(true, missing, missing); workBook = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
public void SaveXls() { string currentDate = DateTime.Now.ToString("MM-yyyy"); string foldername = String.Empty; string initialDirectory = Form1.pathsDictionary["pdf"]; initialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : BaseFunctions.GetRootFolderOfCurrentDisk(); FolderBrowserDialog folder = new FolderBrowserDialog(); folder.ShowNewFolderButton = true; folder.SelectedPath = initialDirectory; if (folder.ShowDialog() == DialogResult.OK) { foldername = folder.SelectedPath; } if (!String.IsNullOrEmpty(foldername)) { Form1.pathsDictionary["pdf"] = foldername; foldername = foldername + String.Format("Боржники станом на {0}", currentDate) + ".pdf"; xlWbk.ExportAsFixedFormat(0, foldername, 0, 0); // сохраняем новый путь // сохранение в INI-при выходе из программы } CloseExcel(); }
/// <summary>把Excel文件转换成PDF格式文件</summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true=转换成功</returns> public static bool Xls2Pdf(string sourcePath, string targetPath) { bool result = false; Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF; object missing = Type.Missing; Excels.ApplicationClass application = null; Excels.Workbook workBook = null; try { application = new Excels.ApplicationClass(); string source = sourcePath; object target = targetPath; object type = targetType; workBook = application.Workbooks.Open(source, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); workBook.ExportAsFixedFormat(targetType, target, Excels.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); result = true; } catch (Exception ex) { result = false; throw ex; } finally { if (workBook != null) { workBook.Close(true, missing, missing); workBook = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
// private Excel.Worksheet sheet; public override void Convert(String inputFile, String outputFile) { Object nothing = Type.Missing; try { if (!File.Exists(inputFile)) { throw new ConvertException("File not Exists"); } if (IsPasswordProtected(inputFile)) { throw new ConvertException("Password Exist"); } app = new Excel.Application(); books = app.Workbooks; book = books.Open(inputFile, false, true, nothing, nothing, nothing, true, nothing, nothing, false, false, nothing, false, nothing, false); bool hasContent = false; foreach (Excel.Worksheet sheet in book.Worksheets) { Excel.Range range = sheet.UsedRange; if (range != null) { Excel.Range found = range.Cells.Find("*", nothing, nothing, nothing, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, nothing, nothing, nothing); if (found != null) hasContent = true; releaseCOMObject(found); releaseCOMObject(range); } } if (!hasContent) throw new ConvertException("No Content"); book.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputFile, Excel.XlFixedFormatQuality.xlQualityMinimum, false, false, nothing, nothing, false, nothing); } catch (Exception e) { release(); throw new ConvertException(e.Message); } release(); }
public static void ConvertExcelToPdf(string excelFileIn, string pdfFileOut) { msExcel.Application excel = new msExcel.Application(); try { excel.Visible = false; excel.ScreenUpdating = false; excel.DisplayAlerts = false; FileInfo excelFile = new FileInfo(excelFileIn); string filename = excelFile.FullName; msExcel.Workbook wbk = excel.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); wbk.Activate(); object outputFileName = wbk.FullName.Replace(".xslx", ".pdf");; msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF; // Save document into PDF Format wbk.ExportAsFixedFormat(fileFormat, outputFileName, missing, missing, missing, missing, missing, missing, missing); object saveChanges = msExcel.XlSaveAction.xlDoNotSaveChanges; ((msExcel._Workbook)wbk).Close(saveChanges, missing, missing); wbk = null; } catch (Exception e) { Console.WriteLine(e); } finally { ((msExcel._Application)excel).Quit(); excel = null; } }
void GenerarReporte() { if (app == null) app = new E.Application(); app.Visible = false; wb = app.Workbooks.Open(@rutas.RutaDeReportes + "\\facapt04.xlsx"); E.Worksheet ws = wb.Worksheets[1]; int index = 8; for (int i = dgvLista.SelectedRows.Count - 1; i >= 0 ; i--) { ws.Range["A" + index].Value2 = dgvLista.SelectedRows[i].Cells[1].Value.ToString(); ws.Range["B" + index].Value2 = dgvLista.SelectedRows[i].Cells[2].Value.ToString(); ws.Range["C" + index].Value2 = dgvLista.SelectedRows[i].Cells[3].Value.ToString(); ws.Range["D" + index].Value2 = dgvLista.SelectedRows[i].Cells[4].Value.ToString(); ws.Range["E" + index].Value2 = dgvLista.SelectedRows[i].Cells[5].Value.ToString(); ws.Range["F" + index].Value2 = dgvLista.SelectedRows[i].Cells[6].Value.ToString(); ws.Range["G" + index].Value2 = dgvLista.SelectedRows[i].Cells[7].Value.ToString(); ws.Range["H" + index].Value2 = dgvLista.SelectedRows[i].Cells[8].Value.ToString(); ws.Range["I" + index].Value2 = DateTime.Parse(dgvLista.SelectedRows[i].Cells[9].Value.ToString()).ToString("dd/MM/yyyy"); if (string.IsNullOrEmpty(dgvLista.SelectedRows[i].Cells[10].Value.ToString() ) || string.IsNullOrWhiteSpace(dgvLista.SelectedRows[i].Cells[10].Value.ToString())) ws.Range["J" + index].Value2 = string.Empty; else ws.Range["J" + index].Value2 = DateTime.Parse(dgvLista.SelectedRows[i].Cells[10].Value.ToString()).ToString("dd/MM/yyyy"); index++; } if (System.IO.File.Exists(System.IO.Path.GetTempPath() + "reporte.xlsx")) System.IO.File.Delete(System.IO.Path.GetTempPath() + "reporte.xlsx"); if (System.IO.File.Exists(@rutas.RutaDeTemp + "/rpt_ProdEmpacado.pdf")) System.IO.File.Delete(@rutas.RutaDeTemp + "/rpt_ProdEmpacado.pdf"); wb.SaveAs(System.IO.Path.GetTempPath() + "reporte.xlsx"); wb.ExportAsFixedFormat(E.XlFixedFormatType.xlTypePDF, @rutas.RutaDeTemp + "/rpt_ProdEmpacado.pdf"); VistasPrevias vp = new VistasPrevias(); vp.Navegar(@rutas.RutaDeTemp + "/rpt_ProdEmpacado.pdf"); vp.ShowDialog(); vp.Dispose(); wb.Close(false); app.Quit(); }
public string GetReport() { try { object misValue = System.Reflection.Missing.Value; _excelApp = new Excel.Application(); _excelBook = _excelApp.Workbooks.Add(misValue); _excelSheet = (Excel.Worksheet)_excelBook.Worksheets.get_Item(1); _excelSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape; _excelApp.Cells[1, 1] = "ЗАО «Специализированная Автошкола»"; _excelApp.Cells[2, 1] = "Юридический адрес:"; _excelApp.Cells[3, 1] = "г. Могилев, ул. Школьная 16-405"; _excelApp.Cells[4, 1] = "УНН: 600359652"; _excelApp.Cells[5, 1] = "Р/с 3012205280013 в Ф-л ОАО Бел"; _excelApp.Cells[6, 1] = "АПБ МОУ г. Могилев,"; _excelApp.Cells[7, 1] = "пр-т Мира 91 код 942"; _excelApp.Cells[8, 1] = "Телефон:(222) 290-45-65"; _excelApp.Cells[9, 1] = "Директор: Хацкевич Андрей Евгеньевич"; _excelApp.Cells[11, 1] = "Расписание теоритических занятий"; _excelApp.Cells[12, 1] = string.Format("на {0} {1} г.", GetMonthName(Month), Year); _excelApp.Cells[14, 1] = "Дата/Время"; _excelApp.Cells.get_Range("A14", "B14").Merge(Type.Missing); _excelApp.Columns[1].ColumnWidth = 15; _excelApp.Cells[14, 1].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[1].VerticalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[2].ColumnWidth = 11; _excelApp.Columns[2].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[2].VerticalAlignment = Excel.Constants.xlCenter; //вывод времени var times = Lessons.Select(l => l.Lessons.Select(t => new { StartTime = t.StartTime, EndTime = t.EndTime, })).SelectMany(t => t.Select(d => d)).Distinct().OrderBy(d => d.StartTime); int col = 3; foreach (var t in times) { _excelApp.Cells[14, col] = t.StartTime.ToString() + "-" + t.EndTime.ToString(); _excelApp.Columns[col].ColumnWidth = 19; _excelApp.Columns[col].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[col].VerticalAlignment = Excel.Constants.xlCenter; col++; } int colCount = col - 1; var cellHeader1 = (Excel.Range)_excelApp.Cells[11, 1]; var cellHeader2 = (Excel.Range)_excelApp.Cells[11, colCount]; _excelApp.Cells.get_Range(cellHeader1, cellHeader2).Merge(Type.Missing); _excelApp.Cells.get_Range(cellHeader1, cellHeader2).HorizontalAlignment = Excel.Constants.xlCenter; cellHeader1 = (Excel.Range)_excelApp.Cells[12, 1]; cellHeader2 = (Excel.Range)_excelApp.Cells[12, colCount]; _excelApp.Cells.get_Range(cellHeader1, cellHeader2).Merge(Type.Missing); _excelApp.Cells.get_Range(cellHeader1, cellHeader2).HorizontalAlignment = Excel.Constants.xlCenter; //вывод дат int row = 15; foreach (var l in Lessons.OrderBy(l => l.Dates.OrderBy(d => d.Day).FirstOrDefault().DayOfWeek)) { _excelApp.Cells[row, 1] = l.DayOfWeek; int rowStart = row; foreach (var d in l.Dates.OrderBy(d => d.Date)) { _excelApp.Cells[row, 2] = d.ToShortDateString(); row++; } int rowEnd = row - 1; _excelApp.Cells.get_Range(string.Format("A{0}", rowStart), string.Format("A{0}", rowEnd)).Merge(Type.Missing); for (int i = 3; i < col; i++) { Excel.Range cellStart = (Excel.Range)_excelApp.Cells[rowStart, i]; Excel.Range cellEnd = (Excel.Range)_excelApp.Cells[rowEnd, i]; _excelApp.Cells.get_Range(cellStart, cellEnd).Merge(Type.Missing); } } //вывод занятий for (int i = 3; i < col; i++) { for (int j = 15; j < row; j++) { string dayOfWeek = _excelApp.Cells[j, 1].Text; string str1 = ((string)_excelApp.Cells[14, i].Text).Substring(0, 8); TimeSpan startTime = TimeSpan.Parse(str1); string str2 = ((string)_excelApp.Cells[14, i].Text).Substring(9, 8); TimeSpan endTime = TimeSpan.Parse(str2); var less = Lessons.Where(l => l.DayOfWeek == dayOfWeek).FirstOrDefault(); if (less != null) { var item = less.Lessons.Where(l => l.StartTime == startTime && l.EndTime == endTime).FirstOrDefault(); if (item != null) { _excelApp.Cells[j, i] = item.Group + "\n" + item.Instructor; } } } } Excel.Range cell1 = (Excel.Range)_excelApp.Cells[14, 1]; Excel.Range cell2 = (Excel.Range)_excelApp.Cells[row - 1, col - 1]; var cells = _excelSheet.get_Range(cell1, cell2); // выделяем cells.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; cells.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; // правая внешняя cells.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; // левая внешняя cells.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; // нижняя внешняя cells.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous; // внутренние вертикальные cells.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous; // внутренние горизонтальные //_excelBook.SaveAs(_saveAsPath); _excelBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, Filename: _saveAsPath); } catch (Exception) { } finally { _excelBook.Close(false); _excelApp.Quit(); } return _saveAsPath; }
public string GetReport() { try { object misValue = System.Reflection.Missing.Value; _excelApp = new Excel.Application(); _excelBook = _excelApp.Workbooks.Add(misValue); _excelSheet = (Excel.Worksheet)_excelBook.Worksheets.get_Item(1); _excelSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlPortrait; _excelApp.Cells[1, 1] = "ЗАО «Специализированная Автошкола»"; _excelApp.Cells[2, 1] = "Юридический адрес:"; _excelApp.Cells[3, 1] = "г. Могилев, ул. Школьная 16-405"; _excelApp.Cells[4, 1] = "УНН: 600359652"; _excelApp.Cells[5, 1] = "Р/с 3012205280013 в Ф-л ОАО Бел"; _excelApp.Cells[6, 1] = "АПБ МОУ г. Могилев,"; _excelApp.Cells[7, 1] = "пр-т Мира 91 код 942"; _excelApp.Cells[8, 1] = "Телефон:(222) 290-45-65"; _excelApp.Cells[9, 1] = "Директор: Хацкевич Андрей Евгеньевич"; _excelApp.Cells[11, 1] = string.Format("График работы инструктора {0}", FIO); _excelApp.Cells[12, 1] = string.Format("с {0} по {1}", StartDate.ToShortDateString(), EndDate.ToShortDateString()); var cellHeader1 = (Excel.Range)_excelApp.Cells[11, 1]; var cellHeader2 = (Excel.Range)_excelApp.Cells[11, 4]; _excelApp.Cells.get_Range(cellHeader1, cellHeader2).Merge(Type.Missing); _excelApp.Cells.get_Range(cellHeader1, cellHeader2).HorizontalAlignment = Excel.Constants.xlCenter; cellHeader1 = (Excel.Range)_excelApp.Cells[12, 1]; cellHeader2 = (Excel.Range)_excelApp.Cells[12, 4]; _excelApp.Cells.get_Range(cellHeader1, cellHeader2).Merge(Type.Missing); _excelApp.Cells.get_Range(cellHeader1, cellHeader2).HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Cells[14, 1] = "Дата"; _excelApp.Columns[1].ColumnWidth = 15; _excelApp.Cells[14, 1].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[1].VerticalAlignment = Excel.Constants.xlCenter; _excelApp.Cells[14, 2] = "Время"; _excelApp.Columns[2].ColumnWidth = 20; _excelApp.Columns[2].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[2].VerticalAlignment = Excel.Constants.xlCenter; _excelApp.Cells[14, 3] = "Тип занятия"; _excelApp.Columns[3].ColumnWidth = 20; _excelApp.Columns[3].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[3].VerticalAlignment = Excel.Constants.xlCenter; _excelApp.Cells[14, 4] = "ФИО курсанта/Группа"; _excelApp.Columns[4].ColumnWidth = 25; _excelApp.Columns[4].HorizontalAlignment = Excel.Constants.xlCenter; _excelApp.Columns[4].VerticalAlignment = Excel.Constants.xlCenter; int row = 15; foreach (var l in Lessons.OrderBy(l => (l.Date + l.StartTime))) { _excelApp.Cells[row, 1] = l.Date.ToShortDateString(); _excelApp.Cells[row, 2] = l.StartTime.ToString() + "-" + l.EndTime.ToString(); _excelApp.Cells[row, 3] = l.Type; _excelApp.Cells[row, 4] = l.Training; row++; } Excel.Range cell1 = (Excel.Range)_excelApp.Cells[14, 1]; Excel.Range cell2 = (Excel.Range)_excelApp.Cells[row - 1, 4]; var cells = _excelSheet.get_Range(cell1, cell2); // выделяем cells.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; cells.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; // правая внешняя cells.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; // левая внешняя cells.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; // нижняя внешняя cells.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous; // внутренние вертикальные cells.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous; // внутренние горизонтальные row++; //_excelBook.SaveAs(_saveAsPath); _excelBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, Filename: _saveAsPath); } catch (Exception) { } finally { _excelBook.Close(false); _excelApp.Quit(); } return _saveAsPath; }