You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 lines
4.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using NetLibrary.Data;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NetLibrary;
namespace TradeManageNew
{
public class ExcelNew
{
#region 导入
public DataTable ImportExcel(string fileName)
{
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt(0);
IEnumerator rows = sheet.GetRowEnumerator();
DataTable dt = new DataTable();
IRow row;
rows.MoveNext();
row = (HSSFRow)rows.Current;
int len = row.LastCellNum;
int j = 0;
for (int i = 0; i < len; i++)
{
ICell cell = row.GetCell(i);
if (cell != null)
{
if (cell.ToString().Trim() == "Tracking ID Charge Description")
{
dt.Columns.Add(cell.ToString().Trim()+j.ToString());
}
else if (cell.ToString().Trim() == "Tracking ID Charge Amount")
{
dt.Columns.Add(cell.ToString().Trim() + j.ToString());
j++;
}
else
{
if (dt.Columns.Contains(cell.ToString().Trim()) == true)
dt.Columns.Add(cell.ToString().Trim() + i.ToString());
else
dt.Columns.Add(cell.ToString().Trim());
}
}
}
while (rows.MoveNext())
{
row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = 0; i < len; i++)
{
ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
//读取Excel格式根据格式读取数据类型
switch (cell.CellType)
{
case CellType.BLANK: //空数据类型处理
dr[i] = "";
break;
case CellType.STRING: //字符串类型
dr[i] = cell.StringCellValue;
break;
case CellType.NUMERIC: //数字类型
if (DateUtil.IsCellDateFormatted(cell))//日期类型
{
dr[i] = cell.DateCellValue;
}
else//其他数字类型
{
dr[i] = cell.NumericCellValue;
}
break;
case CellType.FORMULA:
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(hssfworkbook);
dr[i] = e.Evaluate(cell).StringValue;
break;
default:
dr[i] = "";
break;
}
//if (cell.CellType == CellType.FORMULA || cell.CellType == CellType.NUMERIC)
//{
// dr[i] = cell.DateCellValue;
//}
//else
//{
// dr[i] = cell.ToString().Trim();
//}
}
}
dt.Rows.Add(dr);
}
return dt;
}
#endregion
}
}