现在的位置: 首页 > 综合 > 正文

使用c#读取excel中的数据

2013年10月23日 ⁄ 综合 ⁄ 共 967字 ⁄ 字号 评论关闭

可以采用读取Access的方式读取excel中的数据

首先添加System.Data.OleDb引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string file = @"E:\1.xls";
                OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ file +";Extended Properties=Excel 8.0");
                conn.Open();
                Console.WriteLine("连接成功");
                OleDbCommand comm = new OleDbCommand("Select * from [Sheet1$] where [NO] is not null",conn);
                OleDbDataReader re = null;
                re = comm.ExecuteReader();
                if (re != null)
                {
                    string srt;
                    while (re.Read())
                    {
                        srt = re["修改日期"].ToString();
                        Console.WriteLine(srt);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}




如果不做修改的话以上程序会出现错误:定义了过多字段

我使用的office2007,excel的总列数是1048576,由于在建立Excel时候,执行了插入操作,会是Excel长度超过1048576

因此可以将上边的Select
* from [Sheet1$] where [NO] is not null

改为:Select * from [Sheet1$A:B] where [NO] is not null

A:B表示读取两列

修改后读取的结果:



【上篇】
【下篇】

抱歉!评论已关闭.