C # winformprint excel(use npoi?spire.xls + PrintDocument to print excel directly ),

Source: Internet
Author: User

C # winformprint excel(use npoi?spire.xls + PrintDocument to print excel directly ),

Preface

C # generate and print the Excel report for the winform program. In order not to install the corresponding Office components, I chose NPOI to generate the Excel report and used the PrintDocument control of winform to trigger the printing operation, the difficulty lies in how to convert an excel file to a Graphics object. In NPOI, I only find the settings for excel printing (such as horizontal and vertical), and I also need to open the excel file to trigger the printing operation, however, the project requires printing at a time, instead of using the PrintDocument control. You have to repeat the search to find the class library spire.xls, and finally implement the requirements. If you have any mistakes or more concise methods, please give me some advice.

 

Ideas

Use npoi to generate Excel =, use spire.xlsto convert to image .png = to obtain the generated image, and use the drawimage method of Graphic to operate the image. Of course, if you don't mind, you can skip the image operation.:)= "Print using the print method of the printDocument control (of course, you can directly use spire.xlsto directly generate excel, but the free version of spire.xls has a maximum of 150 lines per sheet)

 

Knowledge Point

[0] NPOI usage

Download: http://npoi.codeplex.com/releases/

[1] printDocument control of winform

Reference: https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-print-a-multi-page-text-file-in-windows-forms

Understanding:

The PrintDocument control defines an object that sends output to the printer. The BeginPrint, PrintPage, and EndPrint methods are available when printdocument is executed. when a Print () Statement is run, check whether the BeginPrint method exists. If yes, call it first. Call the PrintPage method to obtain a blank Graphics object from the PrintPageEcentArgs class. We can operate on the Graphics object (which can be understood as drawing the canvas, graphics objects have built-in methods similar to DrawString and DrawPie). At the end of the PrintPage method, this Graphics object is sent to the print device. After the printing device finishes printing, it checks whether the EndPrint method exists and calls it if it exists.

【2】spire.xls usage

Refer:Http://www.cnblogs.com/asxinyu/p/4346907.html

 

Code

[1] Introduction to the printing control used by winform

 

PrintDocument1: defines an object that sends output to a printer.

PrintPreviewDialog1: displays a dialog box that shows you how the associated document is printed.

PrintDialog1: displays a dialog box that allows you to select a printer and select other print options (such as score and paper direction)

[2] Code display

Background settings of the "Print directly" button

Private void DirectPrint_Click (object sender, EventArgs e) {isprint = false; GenerateExcel_Click (sender, e); // use NPOI to generate an excel if (newsavefilepath! = "" & Isprint = true) {isprint = false; ChangeExcel2Image (newsavefilepath); // use Spire to convert an excel file to an image if (printDialog1.ShowDialog () = DialogResult. OK) {printDocument1.Print (); // print }}}

"Generate excel" button background settings

Private void Generate_Click (object sender, EventArgs e) {CreateExcel (); // use NPOI to generate SaveFileDialog savedialog = new SaveFileDialog (); // The savedialog window that allows you to select an excel save path is displayed. filter = "excel files (*. xlsx) | *. xlsx | All files (*. *) | *. * "; savedialog. restoreDirectory = true; savedialog. fileName = string. format ("sales order approval form {0}", DateTime. now. toString ("yyyyMMddHHmm"); if (savedialog. showDialog () = DialogResult. OK ){
// Newsavefilepath is the excel save path newsavefilepath = savedialog. fileName. toString (). trim (); using (FileStream newfs = new FileStream (newsavefilepath, FileMode. create, FileAccess. readWrite) {singlexssfwk. write (newfs); // Write the generated excel file to newfs. close ();}}}

CreateExcel () method example

Using NPOI. XSSF. UserModel; XSSFWorkbook singlexssfwk; // note that different NPOI versions call different methods. The version used here is 2.1.3.1private void CreatExcel ()
{// Obtain the excel template path string str = System. environment. currentDirectory + "\ XXXX.xlsx"; if (File. exists (str) {using (FileStream fs = new FileStream (str, FileMode. open, FileAccess. read) {singlexssfwk = new XSSFWorkbook (fs); fs. close () ;}// obtain table XSSFSheet xssfsheet = (XSSFSheet) singlexssfwk. getSheetAt (0); // create a row XSSFRow xssfrow1 = (XSSFRow) xssfsheet. getRow (1); // set the content of the cell xssfrow1.GetCell (0 ). setCellValue ("... ");......} else {......}}

Example of ChangeExcel2Image () method

Using Spire. xls; public void ChangeExcel2Image (string filename) {Workbook workbook = new Workbook (); workbook. loadFromFile (filename); Worksheet sheet = workbook. worksheets [0]; sheet. saveToImage (imagepath); // image suffix .bmp, set by yourself
}

 

The printDocument1_PrintPage method is called when printDocument1.Print () is executed.

// Write the screenshot code private void printdocument#printpage (object sender, System. drawing. printing. printPageEventArgs e) {# If region does not need to take an image, you do not need to write the following code for GC. collect (); Graphics g = e. graphics; // imagepath refers to the path using (Bitmap bitmap = new dBitmap (imagepath) of the image converted from excel {// how to capture the Rectangle newarea = new Rectangle (); newarea. X = 0; newarea. Y = 50; newarea. width = bitmap. width; newarea. height = bitmap. height-120; using (Bitmap newbitmap = bitmap. clone (newarea, bitmap. pixelFormat) {g. drawImage (newbitmap, 0, 0, newbitmap. width-200, newbitmap. height-150) ;}# endregion}

 

Note: The Key to setting previewing is that printDocument1 is a global object. You can directly set printPreviewDialog1.Document = printDocument1; printPreviewDialog1.ShowDialog ();. The principle of this is not studied, as long as you have processed the content, you can see it in the preview.

 

Summary

The above is how I implement c # winform to print excel. Maybe this is just a complicated method. If you have a more streamlined method, please don't hesitate to give me some advice. In case of any errors, please do not hesitate to inform us.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.