2023-10-17 15:32:13
浏览数 (3)
導入excel中的數据到DataTable中
代码语言:javascript
复制/// <summary>
/// 導入excel中的數据到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名稱</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
private DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
FileStream fs = null;
ISheet sheet = null;
IWorkbook workbook = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
if (strFileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (strFileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果有找到指定的sheetName名稱的sheet,默認取第一個sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; i )
{
ICell cell = firstRow.GetCell(i);
string cellValue;
if (cell.CellType == CellType.Numeric)
{
DateTime cellDate = Convert.ToDateTime(cell.DateCellValue.ToString());
cellValue = cellDate.ToString("yyyy/MM/dd").Replace("/", "");
}
else
{
cellValue = cell.StringCellValue;
}
if (cell != null || cell.DateCellValue.ToString() == "")
{
if (cellValue != null || cell.DateCellValue.ToString() == "")
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的標號
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; i )
{
IRow row = sheet.GetRow(i);
string ss = row.GetCell(0).ToString();
if (row != null)
{
if (ss != "")
{
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j )
{
if (row.GetCell(j) != null)//同理沒有數据的行默認是null
{
dataRow[j] = row.GetCell(j).ToString();
}
}
data.Rows.Add(dataRow);
}
}
else
{
break;
}
}
}
if (fs != null) fs.Close();
return data;
}
catch (Exception ex)
{
if (fs != null) fs.Close();
Console.WriteLine("Exception: " ex.Message);
return null;
}
}