excel导入导出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FS.Extend;
using System.Data;
using System.Data.OleDb;
namespace Tag.Logic
{
    public static class UploadFileLogic
    {
        /// <summary>
        /// 获取链接字符串
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        private static string GetConectionString(string filePath)
        {
            var strSuffix = "";
            if (filePath.IsNullOrEmpty()) { return ""; }
            strSuffix = filePath.Substring(filePath.LastIndexOf("."));
            var strConectionString = "";
            switch (strSuffix)
            {
                case ".xls":
                    {
                        strConectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties="Excel 8.0"";
                        break;
                    }
                case ".xlsx":
                    {
                        strConectionString = "Provider=Microsoft.Jet.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0"";
                        break;
                    }
            }
            return strConectionString;
        }
        /// <summary>
        /// 获取表数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="sheetName">名称</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string filePath, string sheetName)
        {
            string strConn = GetConectionString(filePath);
            string strSql = "select * from [" + sheetName + "$]";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable dt = new DataTable();
            OleDbDataAdapter ole = new OleDbDataAdapter(strSql, conn);
            ole.Fill(dt);
            return dt;
        }
    }
}

 var licenseDT = new DataTable();

licenseDT = UploadFileLogic.GetDataTable(pathfile, "证书信息");

原文地址:https://www.cnblogs.com/sll-fuling/p/5033383.html