2.3.2 use npoi to operate the Excel-sum function

Source: Internet
Author: User

In this section, we will start to learn the most commonly used sum function in Excel.

First, let's first look at the simplest sum function: sum (num1, num2 ,...). Effect

E1 = sum (A1, C1) in the figure indicates filling the sum of A1 and C1 at E1, which is equivalent to the formula "e1 = A1 + C1. Corresponding generationCodeSimilar to the basic calculation formula in the previous section:

 

Hssfsheet sheet1 = Hssfworkbook. createsheet ( " Sheet1 " );
Hssfrow row1
= Sheet1.createrow ( 0 );
Hssfcell cel1
= Row1.createcell ( 0 );
Hssfcell cel2
= Row1.createcell ( 1 );
Hssfcell cel3
= Row1.createcell ( 2 );
Hssfcell celsum1
= Row1.createcell ( 3 );
Hssfcell celsum2
= Row1.createcell ( 4 );
Hssfcell celsum3
= Row1.createcell ( 5 );

Cel1.setcellvalue (1);
Cel2.setcellvalue (
2);
Cel3.setcellvalue (
3);
Celsum2.setcellformula (
"Sum (A1, C1)");

Of course, it is easy to understand that every cell is used as a parameter of the sum function. However, if there are many required cells, the formula will be very long, which is neither easy to read nor to write. Therefore, Excel provides another method to sum multiple cells:

For example, sum (A1: C1) indicates the sum of all cells from A1 to C1, which is equivalent to A1 + B1 + C1.
The corresponding code is:

 

Celsum1.setcellformula ( " Sum (A1: C1) " );

Finally, there is a method for summation. Define an area, such as "range1", and then set sum (range1). Then, the sum of all cells in the area is calculated.
The code for defining a region is:

Hssfname range = Hssfworkbook. createname ();
Range. Reference
=   " Sheet1! $ A1: $ C1 " ;
Range. namename
=   " Range1 " ;

After the code is executed, the Excel file is displayed in the name Manager (excel2007 menu path, 2003 slightly different) under the formula menu:
 
Add the formula to cell F1:

Celsum3.setcellformula ( " Sum (range1) " );

Shows the generated Excel file:
 

 

Returned directory

 

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.