亲宝软件园·资讯

展开

c#读取excel内容 c#读取excel内容内容示例分享

人气:0
想了解c#读取excel内容内容示例讲解的相关内容吗,在本文为您仔细讲解c#读取excel内容的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c#,读取excel,下面大家一起来学习吧。

1、Excel 需是.xls 格式
2、添加引用Microsoft.Office.Interop.Excel.dll

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;

namespace ReadExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"D:\TransferPlant\111.xls";
            DataTable dt = ExcelToDataSet(fileName);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Console.WriteLine(dt.Rows[i][0].ToString());
                }
            }
        }

        static public DataTable ExcelToDataSet(string filename)
        {
            string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+filename+";Extended Properties=Excel 8.0";
            OleDbConnection conn = new OleDbConnection(strCon);
            conn.Open();
            //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等 
            DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
            //包含excel中表名的字符串数组
            string[] strTableNames = new string[dtSheetName.Rows.Count];
            for (int k = 0; k < dtSheetName.Rows.Count; k++)
            {
                strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
            }
            OleDbDataAdapter myCommand = null;
            DataTable dt = new DataTable();
            //从指定的表明查询数据,可先把所有表明列出来供用户选择
            string strExcel = "select * from [" + strTableNames[0] + "]";
            myCommand = new OleDbDataAdapter(strExcel, strCon);
            myCommand.Fill(dt);

            return dt;
        }
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论