使用NPOI导入Excel注意日期格式和数字格式

时间:2023-03-09 15:08:41
使用NPOI导入Excel注意日期格式和数字格式
//使用NPOI导入Excel
public static DataTable importExcelToDataSetUsingNPOI(string FilePath, string fileName)
{
DataSet myDs = new DataSet();
DataTable dt = new DataTable("mytable"); myDs.Tables.Add(dt);
DataRow myRow;
myDs.Clear(); try
{
using (Stream stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook wk = new HSSFWorkbook(stream); ISheet sheet = wk.GetSheetAt(); //读取当前表数据 只读取第一个sheet int rowsint = sheet.LastRowNum;
for (int y = ; y <= rowsint; y++)
{
//Execel第一行是标题,不是要导入数据库的数据
IRow row = sheet.GetRow(y); //读取当前行数据
if (row != null)
{
int columnsint = row.LastCellNum;
if (y == )//第一行,标题
{
for (int m = ; m < columnsint; m++)
{
dt.Columns.Add("F" + m.ToString(), System.Type.GetType("System.String"));
}
}
else
{
myRow = myDs.Tables["mytable"].NewRow();
for (int j = ; j < columnsint; j++)
{
if (j == )
{ }
if (row.GetCell(j).CellType == CellType.NUMERIC)//数字类型
{
string columnname = "F" + j.ToString();
if (DateUtil.IsValidExcelDate(row.GetCell(j).NumericCellValue) && DateUtil.IsCellDateFormatted(row.GetCell(j)))
{
DateTime D = row.GetCell(j).DateCellValue;
myRow[columnname] = (D.ToString().Length == || D.ToString().Contains("#")) ? " " : D.ToString();
}
else
{
double strValue = row.GetCell(j).NumericCellValue;
myRow[columnname] = (strValue.ToString().Length == || strValue.ToString().Contains("#")) ? " " : strValue.ToString();
}
}
else
{
string strValue = row.GetCell(j).StringCellValue;
string columnname = "F" + j.ToString();
myRow[columnname] = (strValue.Length == || strValue.Contains("#")) ? " " : strValue;
}
}
try
{
myDs.Tables["mytable"].Rows.Add(myRow);
}
catch { }
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return myDs.Tables["mytable"];
}