Second, the specific steps to import data from Excel into a database:
protected void Button1_Click (object sender, EventArgs e)
{
Try
{
File stream
using (Stream stream = new FileStream (@ "G:\userInfo.xls", FileMode.Open, FileAccess.Read))
{
Hssfworkbook workbook = new Hssfworkbook (stream);
Hssfsheet sheet = workbook. Getsheetat (0);
Execel The first row is the title, not the data to import the database
for (int i = 1; I <= sheet. Lastrownum; i++)
{
Hssfrow row = sheet. GetRow (i);
UserInfo UserInfo = new UserInfo ();
UserInfo. UserName = row. Getcell (0). Stringcellvalue;
Determine the type of age in Excel, depending on the type, to take the values in different ways
if (row. Getcell (1). Celltype = = hssfcell.cell_type_numeric)
{
UserInfo. Age = row. Getcell (1). Numericcellvalue;
}
Else
{
UserInfo. Age =convert.toint32 (row. Getcell (1). Stringcellvalue);
}
UserInfo. Email = row. Getcell (2). Stringcellvalue;
The same goes for phone numbers
if (row. Getcell (3). Celltype = = hssfcell.cell_type_numeric)
{
UserInfo. Telephone = row. Getcell (3). Numericcellvalue.tostring ();
}
Else
{
UserInfo. Telephone = row. Getcell (3). Stringcellvalue;
}
UserInfo. Adddate = row. Getcell (4). Datecellvalue;
UserInfo. Address = row. Getcell (5). Stringcellvalue;
Note: The space in Excel can be empty, remark can not be filled, so we need to judge.
if (row. Getcell (6) ==null)
{
UserInfo. Remarks = "";
}
Else
{
UserInfo. Remarks = row. Getcell (6). Stringcellvalue;
}
New Userinfobll (). AddNew (userinfo);
}
}
Response.Write ("Import data Success");
}
catch (Exception ex)
{
Response.Write ("Error:" + ex.) Message);
}
}
Another method:
Aspose
Npoi importing Excel into the database