c# 一个通过oledb读取excel,csv的类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace SyncCardService
{
    public class ExcelReader
    {
        private string filePath;
        private string fileName;
        private OleDbConnection conn;
        private DataTable readDataTable;
        private string connString;
        private FileType fileType = FileType.noset;

        public ExcelReader()
        {
            
        }

        private void SetFileInfo(string path)
        {
            filePath = path;

            fileName = this.filePath.Remove(0, this.filePath.LastIndexOf("\\") + 1);
            switch (fileName.Split('.')[1])
            {
                case "xls": connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; fileType = FileType.xls;
                    break;
                case "xlsx": connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; fileType = FileType.xlsx;
                    break;
                case "csv": connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath.Remove(filePath.LastIndexOf("\\") + 1) + ";Extended Properties='Text;FMT=Delimited;HDR=YES;'"; fileType = FileType.csv;
                    break;
            }
        }


        public DataTable ReadFile(string path)
        {
            if (System.IO.File.Exists(path))
            {
                SetFileInfo(path);
                OleDbDataAdapter myCommand = null;
                DataSet ds = null;

                using (conn = new OleDbConnection(connString))
                {
                    conn.Open();

                    DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                    string tableName = fileType == FileType.csv ? fileName : schemaTable.Rows[0][2].ToString().Trim();

                    string strExcel = string.Empty;

                    strExcel = "Select   *   From   [" + tableName + "]";
                    myCommand = new OleDbDataAdapter(strExcel, conn);

                    ds = new DataSet();

                    myCommand.Fill(ds, tableName);

                    readDataTable = ds.Tables[0];

                }
            }
            return readDataTable;
        }

        private enum FileType
        {
            noset,
            xls,
            xlsx,
            csv
        }

    }
}


转载于:https://www.cnblogs.com/hanwest/archive/2012/08/30/2881887.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值