Excel converts to table (removes a row of values that are empty for all column values, that is, a DataTable that returns a valid value)

Source: Internet
Author: User

<summary>
Removes a row of values that are NULL for all column values, that is, a DataTable that returns a valid value
</summary>
<param name= "Stream" ></param>
<returns></returns>
public static DataTable streamtodatatabletrimtr (Stream stream)
{
The first line is generally the header row.
DataTable table = new DataTable ();
Table. TableName = "Dealer Information Form";
Create Hssfworkbook, the entire Excel document, based on the path through existing Excel
Iworkbook workbook = new Xssfworkbook (stream);
Hssfworkbook workbook = new Hssfworkbook (File.Open (FilePath, FileMode.Open));//The path to the file can be passed here

Xssfsheet sheet = (xssfsheet) workbook. Getsheetat (0);
//Gets the first sheet of Excel
//Gets the maximum number of rows in Excel
int rowscount = sheet. Physicalnumberofrows;
//To ensure that the table layout is the same as Excel, you should take the maximum number of columns in all rows (you need to traverse the entire sheet).
//For less than a full Excel traversal to improve performance, we can artificially adjust the number of columns in line No. 0 to the maximum number of columns in all rows.
int colscount = sheet. GetRow (0). Physicalnumberofcells;
for (int i = 0; i < Colscount; i++)
{
table. Columns.Add (i.ToString ());
}
for (int x = 0; x < Rowscount; + +)
{
if (sheet. GetRow (x)! = null)
{
DataRow dr = table. NewRow ();
bool Trisnull = false;
for (int y = 0; y < colscount; y++)
{
String content = (Null = = Sheet. GetRow (x). Getcell (y))? "": Sheet. GetRow (x). Getcell (y). ToString (). Trim ();
if (!string. IsNullOrEmpty (content))
Trisnull = true;
Dr[y] = content;
}
if (trisnull)//A row has a value that is not empty, create a new line
table. Rows.Add (DR);
}
}
sheet = null;
workbook = null;
return table;
}

Excel converts to table (a DataTable that returns a valid value if all column values are blank)

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.