C # For Beginners, because the project requires Excel operations. I searched the internet and found a lot of materials. However, the writing is too redundant, and it is a big headache to cut off the code,
Summary: I forgot to add the deficiencies.
Considering compatibility issues, for office2003 operations
--- Required library Microsoft. Office. InterOP. Excel. dll (Attachment)
---- Classes used in the code
C # code
- Using system;
- Using system. drawing;
- Using system. collections;
- Using system. componentmodel;
- Using system. Data;
- Using system. IO;
- Using system. text;
- Using system. windows;
- Using system. reflection;
- Using system. runtime. interopservices;
- Using Excel = Microsoft. Office. InterOP. Excel;
Create a new Excel File
(Code snippet 1)
C # code
- Object missing = missing. value;
- Excel. Application m_objexcel = new excel. Application ();
- Excel. workbooks m_objworkbooks = m_objexcel.workbooks;
- Excel. Workbook m_objworkbook = m_objworkbooks.add (true );
- Excel. Sheets m_objworksheets = m_objworkbook.sheets ;;
- Excel. worksheet m_objworksheet = (Excel. worksheet) m_objworksheets [1];
- Try
- {
- M_objexcel.save ("F: 129.xls ");
- }
- Catch (exception E)
- {
- }
- Finally {
- M_objworkbooks.close ();
- M_objexcel.quit ();
- }
------ Operate the cell to navigate by horizontal and vertical coordinates
Add the following code before try {} catch () {}
(Code snippet 2)
C # code
- M_objexcel.cells [1, 1] = "Building Energy evaluation and calculation report"; // value assignment in the first column of the first line
------ Merge cells (Add the following code before try {} catch)
C # code
- M_objexcel.cells [1, 1] = "Building Energy conservation evaluation and calculation report ";
- Excel. Range = m_objexcel.get_range (m_objexcel.cells [1, 1], m_objexcel.cells [1, 10]);
- Range. Merge (type. Missing); // merge Cells
--- Operation font size, color, cell background color. Border color (Add the following code before try {} catch)
Java code
- M_objexcel.cells [1, 1] = "Building Energy conservation evaluation and calculation report ";
- Excel. Range = m_objexcel.get_range (m_objexcel.cells [1, 1], m_objexcel.cells [1, 10]);
- Range. Merge (type. Missing); // merge Cells
- Range. Font. size = 25; // font size
- Range. horizontalalignment = excel. constants. xlcenter; // align
- Range. Font. Bold = 17; // font size
- // Range. Borders. linestyle = excel. xllinestyle. xlcontinuous; // border
- // Range. Borders. Color = colortranslator. Toole (color. Red); // border color
- // Range. Interior. colorindex = 34; background color