使用c#读取excel中的数据

可以采用读取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表示读取两列

修改后读取的结果:



  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值