[Non-paid] Two methods of converting Excel to PDF in C#

Preface: In fact, there are many software suites that provide Excel to PDF conversion, and also include more powerful APIs for file format conversion and operation, such as ITextshape, sautinsoft, evopdf, and componentpro
. But they are all paid for by business. I only found two methods that can be used in the morning, so I will record them for now.

一.Microsoft.Office.Interop.Excel

This is a dll provided by Microsoft for operating Excel. There are methods in it to convert Excel directly into PDF files.

//参数全为Object,非常难以理解
void ExportAsFixedFormat(XlFixedFormatType Type, object Filename, object Quality, object IncludeDocProperties, object IgnorePrintAreas, object From, object To, object OpenAfterPublish, object FixedFormatExtClassPtr);

Use example:

static void Main(string[] args)
{
    
    
   
    string sourcexlsx = $@"C:\XXXXX\TKONE.xlsx";

    string targetpdf = $@"C:\XXXXXX\target.pdf";

    Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.Application();

    Microsoft.Office.Interop.Excel.Workbook workbook = appExcel.Workbooks.Open(sourcexlsx);
	//也可以选择转化为XPS模式
    workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetpdf);

    workbook.Close();

    appExcel.Quit();

}

Please add image description
Please add image description
Because the table in the picture is very long, it is truncated to three pages after being converted to PDF , and the other parameters mentioned above have no effect on the truncation.
If you want to know about other parameters, please see the following link:
Conversion Microsoft documentation for the method

二.Free Spire.XLS

Spire is also a paid API for various document operations, but fortunately it has a free version with very limited functions [Free version is limited to 5 sheets per workbook and 200 rows per sheet.] (it can also be used commercially) , if there is not much content, the basic impact will not be very big,
announcement portal
usage examples:

 Spire.Xls.Workbook book = new Spire.Xls.Workbook();
 book.LoadFromFile($@"C:\XXXXXX\TKONE.xlsx");
 book.ConverterSetting.SheetFitToPage = true; //可以设置适应页面
 book.SaveToFile($@"C:\XXXXXXXXXX\dark.pdf", Spire.Xls.FileFormat.PDF);
 book.Save();

The obtained conversion result is:
Please add image description
the width is adaptive, and the method is simpler to use. It is still very convenient if you only convert a single simpler file. If it still cannot meet your needs, you may need to choose a paid API.

Guess you like

Origin blog.csdn.net/jamenu/article/details/128520616