读取Excel文件转成DataTable

DataSet ds=new DataSet();
    string connStr="provider=MicroSoft.Jet.OLEDB.4.0;Data Source="+strFileName+";Extended Properties=Excel 8.0";
    
    string commStr="select * from ["+GetResellerType(ResellerType)[1].ToString()+string.Format("$] where 渠道编号<>'' ",ResellerType);       
    
    OleDbConnection myConn=new OleDbConnection(connStr);
    OleDbCommand myComm=new OleDbCommand(commStr);
    OleDbDataAdapter myAd=new OleDbDataAdapter(commStr,connStr);
    myAd.Fill(ds);
    myConn.Close();
    return ds.Tables[0];

转载于:https://www.cnblogs.com/yuanweisen/archive/2009/03/03/1402239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 NPOI 库来读取文件 ExcelDataTable。 以下是一个简单的示例代码: ```csharp using System.Data; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; public static DataTable ReadExcelToDataTable(string filePath, string sheetName) { DataTable dt = new DataTable(); IWorkbook workbook = null; ISheet sheet = null; int columnCount = 0; int rowCount = 0; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { workbook = new XSSFWorkbook(fs); } sheet = workbook.GetSheet(sheetName); if (sheet != null) { rowCount = sheet.LastRowNum + 1; for (int i = 0; i < rowCount; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = null; if (i == 0) { columnCount = row.LastCellNum; for (int j = 0; j < columnCount; j++) { ICell cell = row.GetCell(j); if (cell != null) { dt.Columns.Add(cell.ToString()); } } } else if (row != null) { dataRow = dt.NewRow(); for (int j = 0; j < columnCount; j++) { ICell cell = row.GetCell(j); if (cell != null) { dataRow[j] = cell.ToString(); } } dt.Rows.Add(dataRow); } } } return dt; } ``` 这个示例代码假设您使用 XLSX 格式的文件,如果您使用 XLS 格式的文件,则需要将 `XSSFWorkbook` 替换为 `HSSFWorkbook`。此外,这个示例代码假设您知 Excel 文件中要读取的工作表的名称。如果您不知工作表的名称,可以使用 `workbook.GetSheetAt(index)` 方法来获取工作表,其中 `index` 是从 0 开始的工作表序号。 请注意,如果您想读取大型 Excel 文件,建议使用分段读取的方式,而不是一次读取整个文件。这样可以避免内存溢出的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值