Example of C# operation excel printing
using System; using ; using ; using ; using ; using ; using ; using Excel = ; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private bool isStartPrint = false; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //string OriginalPath = () + "\\"; //// Initialize the database //(OriginalPath); //(); //int k=("select * from ElementInventory").; //Initialize the data to be written to Excel DataTable dt = new DataTable(); for (int i = 0; i < 11; i++) { DataColumn dc = new DataColumn(); = "name" + i; = typeof(string); (dc); } for (int i = 0; i < 30; i++) { DataRow dr = (); if (i % 2 == 0) { dr[0] = "Test Cases" + i + "Sign, start testing whether the line wraps are automatically and the page is highly adaptable."; } else { dr[0] = "Test Cases" + i + "Number"; } for (int j = 1; j < 11; j++) { dr[j] = j; } (dr); } if (!isStartPrint) { Thread th = new Thread(delegate () { DataTabletoExcel(dt, "Test.xlsx"); }); (); isStartPrint = true; } else { ("The print program is enabled, please wait...", "hint", , ); } //DataTabletoExcel(dt, "test.xlsx"); } public void DataTabletoExcel( dtTemp, string strFileName) { int rowNum = ; //First get the number of rows of dtTemp int columnNum = ; //Number of columns ExcelApp = new (); //Declare an application class instance // = ""; // The default file path to export excel is still set in the parameter strFileName // = true; // = 1;/// Return or set the number of worksheets that Microsoft Excel automatically inserts into a new workbook. worksBook = (); //Create a new workbook workSheet = ()[1]; //Get sheet in the workbook. if (workSheet == null) { ("ERROR: worksheet == null"); return; } = "Test Sheet1"; //The name of the worksheet = true; //Set all columns' text wrapping automatically (); //Set all columns to automatically adjust row height #region Draw columns ///Customize method, draw columns into sheet RangeMark(workSheet, "A1", "A2", "Merge Vertical Column 1"); RangeMark(workSheet, "B1", "B2", "Merge Vertical Column 2"); RangeMark(workSheet, "C1", "C2", "Merge Vertical Column 3"); RangeMark(workSheet, "D1", "D2", "Merge Vertical Column 4"); RangeMark(workSheet, "E1", "E2", "Merge Vertical Column 5"); RangeMark(workSheet, "F1", "H1", "Merge 1"); RangeMark(workSheet, "F2", "F2", "Merge 1.1"); RangeMark(workSheet, "G2", "G2", "Merge 1.2"); RangeMark(workSheet, "H2", "H2", "Merge 1.3"); RangeMark(workSheet, "I1", "K1", "Merge 2"); RangeMark(workSheet, "I2", "J2", "Merge 2.1"); RangeMark(workSheet, "K2", "K2", "Merge 2.2"); #endregion //Import the data in DataTable into Excel for (int i = 0; i < rowNum; i++) { for (int j = 0; j < columnNum; j++) { [i + 3, j + 1] = [i][j].ToString(); //text } } ///Save path string filePath = @"C:\Users\Admin\Desktop\" + strFileName; if ((filePath)) { try { (filePath); } catch (Exception) { } } = true; //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- = .xlPaperA4;//Paper size = ;//The page horizontal // = 75; //Page setting when printing, what percentage of the zoom ratio = false; //The page setting must be set to false, the page height and page width are valid when printing. = 1; //Set the page size to 1 page width = false; //Set page height automatically for page zoom = "Nigel";//The logo on the top left of the page = "Page &P of &N";//Page Subscript = true; //Print cell mesh line = 1.5 / 0.035; //The upper margin is 2cm (convert to in) = 1.5 / 0.035; //The bottom margin is 1.5cm = 2 / 0.035; //The left margin is 2cm = 2 / 0.035; //The right margin is 2cm = true; //The text is centered //----------------------------------------------------------------------------------------------------------------------------- ////wanmingtom/article/details/6125599 (); //Print preview //(); //Print directly //(); //Close the workspace //(); //Exit the program //(filePath); //Save table KillProcess(ExcelApp); //Kill the generated process isStartPrint = false; //Print finished (); //Garbage recycling mechanism } /// <summary> /// Reference Windows handle to get the program PID /// </summary> /// <param name="Hwnd"></param> /// <param name="PID"></param> /// <returns></returns> [DllImport("")] public static extern int GetWindowThreadProcessId(IntPtr Hwnd, out int PID); /// <summary> /// Kill the generated process /// </summary> /// <param name="AppObject">Process Object</param> private static void KillProcess( AppObject) { int Pid = 0; IntPtr Hwnd = new IntPtr(); p = null; try { GetWindowThreadProcessId(Hwnd, out Pid); p = (Pid); if (p != null) { (); (); } } catch (Exception ex) { ("Process shutdown failed! Exception message:" + ex); } } /// <summary> /// Create header cells, including merged cells /// </summary> /// <param name="workSheet">worksheet</param> /// <param name="startCell">Cell start cell number</param> /// <param name="endCell">Cell end number</param> /// <param name="strText">Cell name</param> private static bool RangeMark( workSheet, string startCell, string endCell, string strText) { //Create a zone object. The first parameter is the start grid number, and the second parameter is the end grid number. For example, select the area A1-D3. range = ()workSheet.get_Range(startCell, endCell); if (range == null) { ("ERROR: range == null"); return false; } (0); //Merge method, when 0 is 0, merge it into a cell = 16; //Font size = "Bold"; //Font = true; // Text wrapping automatically (); //Automatically adjust the row height // = 20; //(); //Automatically adjust column width = 15; = ; //Horizontal center = strText; //After merging cells, set the text in it = 20; //Fill color = 1; //Set the thickness of the cell border return true; } } }
The above is the detailed content of the C# operation excel printing example. For more information about C# printing, please follow my other related articles!
Related Articles
C# uses generic implementation to delete duplicate elements in an array
This article mainly introduces in detail how C# uses generics to delete duplicate elements in an array. The sample code in the article is explained in detail. Interested friends can follow the editor to learn it.2024-02-02C# Panel implementation of the example method of using mouse to operate scroll bars in WinForm
Since Panel cannot directly respond to the scroll event of the mouse in WinForm, it has to use the scroll event of the form to capture the scroll event.2013-03-03Use C# 11's static interface method to improve the convention-oriented design method
We know that interfaces are defined for contracts, but they can only define a set of "instances" contracts, but not a type of contract, because the method defined in the interface can only be the instance party. This article mainly introduces the use of C# 11's static interface method to improve the design of conventions. Friends who need it can refer to it.2022-12-12C# realizes a simple student achievement management system
This article mainly introduces C# to implement a simple student achievement management system. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.2022-08-08ListView control implementation form code in C#
This article mainly introduces the core code of the ListView control implementation form in C#. It is very good and has reference value. Friends who are interested in the knowledge related to c# listview, let’s learn together.2016-08-08How to read and write text files in C#
This article mainly introduces the methods of reading and writing text files in C#, and analyzes the principles and implementation techniques of C# operating text files in an example. Friends who need it can refer to it.2015-06-06Detailed explanation of C# using timer
In the past, we usually used it as a timer, but in fact, it can also implement the timer function. Let’s follow the editor to learn how to use it to implement the timer function.2024-01-01Example analysis of transaction and non-transaction processing methods in C#
This article mainly introduces transaction processing and non-transaction processing methods in C#, and analyzes the usage skills of transaction processing and non-transaction processing in C# in a more detailed manner. It has certain reference value for using C# for database program development. Friends who need it can refer to it.2015-07-07C# method to simply merge word documents
This article mainly introduces C# to implement simple merging of word documents, involving C#’s techniques for reading, inserting, saving word documents, etc., which is very practical. Friends who need it can refer to it.2015-09-09A brief introduction to C# keyword Check
This article mainly introduces the description and precautions of the C# keyword Check function. The check keyword is mainly used to explicitly enable overflow checking for integer type arithmetic operations and conversions. This article will introduce it in detail through the program demonstration. Let’s take a look at it if you need it.2022-04-04