SoFunction
Updated on 2025-03-08

How to print excel in C# winform

Preface

C# does winform program to generate and print Excel reports. In order not to install the corresponding components of Office, I chose NPOI to generate Excel reports and used winform's PrintDocument control to trigger the printing operation. The difficulty lies in how to convert excel into Graphics object. In NPOI, I only found the settings for excel printing (such as horizontal/portrait). I also need to open excel to trigger the printing operation. However, the project requirement is to directly implement printing at one time. I need to use the PrintDocument control instead of operating excel again. I had to search again, found the class library, and finally realized the requirements. If you have any mistakes or more concise methods, please give me some advice.

Ideas

Use npoi to generate Excel =》 Use convert to picture.png =》 to get the generated picture and use Graphic's drawimage method to operate the picture. Of course, if you don't mind, you can not operate the picture:) =》 Use the print method of the printDocument control to implement printing (of course, you can directly generate Excel here, but the free version has a limit of up to 150 lines per sheet)

Knowledge points

【0】NPOI usage method

download:/releases/

【1】winform's printDocument control

refer to:/en-us/dotnet/framework/winforms/advanced/how-to-print-a-multi-page-text-file-in-windows-forms

understand:

The function of the PrintDocument control is to define an object that sends output to the printer, including BeginPrint, PrintPage, and EndPrint methods. When executing the () statement, it will check whether the BeginPrint method exists, and call it first if it exists. Then call the PrintPage method, which will get a blank Graphics object into the PrintPageEcentArgs class. We can operate on the Graphics object (it can be understood that the canvas is drawn. The Graphics object has built-in methods like DrawString and DrawPie). At the end of the PrintPage method, this Graphics object will be sent to the printing device. After the printing device completes printing, it will check whether the EndPrint method exists and calls it if it exists.

【2】How to use

refer to:Tutorial for getting started with .NET Reading and Write Excel Tools (1)

Specific code

【1】Introduction to the printing controls used by winform

Screenshot of plugin used

printDocument1 function: defines an object that sends output to the printer

printPreviewDialog1 function: display a dialog box to show the user the printing of the associated document to the user

printDialog1 function: displays a dialog box that allows the user to select the printer and select other printing options (such as scores, paper direction)

【2】Code display

Background settings of the "Direct Print" button

private void DirectPrint_Click(object sender, EventArgs e)
{
isprint = false;
GenerateExcel_Click(sender, e); //Use NPOI to generate excelif (newsavefilepath != "" && isprint==true)
{
isprint = false; 
ChangeExcel2Image(newsavefilepath); //Use Spire to convert excel into picturesif (() == )
{ 
(); //Print}
} 

}

"Generate Excel" button background settings

private void Generate_Click(object sender, EventArgs e)
{
CreateExcel(); //Use NPOI to generate excel contentSaveFileDialog savedialog = new SaveFileDialog(); //The window pops up to let the user choose the excel save path = " excel files(*.xlsx)|*.xlsx|All files(*.*)|*.*";
 = true;
 = ("Sales Order Approval Form{0}", ("yyyyMMddHHmm"));
if (() == )
{
//newsavefilepath is the save path of excelnewsavefilepath = ().Trim();
using (FileStream newfs = new FileStream(newsavefilepath, , ))
{
(newfs); //Write the generated excel into the file path selected by the user to save();
}
} 
}

CreateExcel() method example

using ;

XSSFWorkbook singlexssfwk;

//Note that the methods called by different NPOI versions are inconsistent, the version used here is 2.1.3.1private void CreatExcel() 
{ 
//Get the path to the template excelstring str =  + "\\";
if ((str))
{
using (FileStream fs = new FileStream(str, , ))
{
singlexssfwk = new XSSFWorkbook(fs);
();
}
//Get the tableXSSFSheet xssfsheet = (XSSFSheet)(0);
//Create a rowXSSFRow xssfrow1 = (XSSFRow)(1);
//Set cell content(0).SetCellValue("...");
... ...
  }
else{
... ...
}
}

Example of ChangeExcel2Image() method

using ; 
public void ChangeExcel2Image(string filename)
{
Workbook workbook = new Workbook();
(filename);
Worksheet sheet = [0];
(imagepath); //Image suffix.bmp, imagepath set by yourself}

The method that executes() will call the printDocument1_PrintPage method

//Write the code to capture the picture in the PrintPage methodprivate void printDocument1_PrintPage(object sender,  e)
{ 
#region If you don't need to capture images, you don't need to write the following code();
Graphics g = ; 
//imagepath refers to the path of the image converted from excelusing (Bitmap bitmap = new dBitmap(imagepath))
{
//How to intercept and explore yourselfRectangle newarea = new Rectangle();
 = 0;
 = 50;
 = ;
 =  - 120;
using (Bitmap newbitmap = (newarea, ))
{
(newbitmap, 0, 0,  - 200,  - 150);
}
} 
#endregion
}

Note: Regarding the setting of preview, the key is that printDocument1 is a global object. Just set = printDocument1; (); directly. The principle of this has not been studied. Anyway, after setting this way, as long as you process the content, you can see it in the preview.

Summarize

The above is my implementation of C# winform printing excel. Perhaps this is just a more complicated method. If there are big guys who have a more streamlined method, please give me some advice. If there is any error, please give me some advice.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.