有些时候不想使用第三方组件来操作Excel,微软Office自带的库是一个不错的选择。可以在传统的WindowsFrom中使用,也可以在WPF中使用。

1. 首先的添加 Microsoft.Office.Interop.Excel 组件

2. WindowsForm 创建的项目

Excel内容如下:

实现读取Excel中内容,显示在UI DataGridView上。

完整代码如下:

using System;using System.Data;using System.Windows.Forms;using Excel = Microsoft.Office.Interop.Excel;using System.Data.OleDb;using System.IO;namespace 使用微软数据引擎操作Excel{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void btnRead\_Click(object sender, EventArgs e){string filePath = string.Empty;string fileExt = string.Empty;OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user {filePath = file.FileName; //get the path of the file fileExt = Path.GetExtension(filePath); //get the file extension if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0){try{DataTable dtExcel = new DataTable();dtExcel = ReadExcel(filePath, fileExt); //read excel file dataGridView1.Visible = true;dataGridView1.DataSource = dtExcel;}catch (Exception ex){MessageBox.Show(ex.Message.ToString());}}else{MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error }}}public DataTable ReadExcel(string fileName, string fileExt){string conn = string.Empty;DataTable dtexcel = new DataTable();if (fileExt.CompareTo(".xls") == 0){//for below excel 2007 conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';";// “HDR =Yes;” 表示第一行包含列名,而不是数据。“HDR =No;” 表明相反;}else{//for above excel 2007 conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";}using (OleDbConnection con = new OleDbConnection(conn)){try{OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select \* from \[Sheet1$\]", con); //here we read data from sheet1 oleAdpt.Fill(dtexcel); //fill excel data into dataTable }catch (Exception ex){MessageBox.Show(ex.Message);}}return dtexcel;}private void btnClose\_Click(object sender, EventArgs e){this.Close();}}}

3. 问题处理

未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。

将项目生成平台该为 X64即可

4. WPF项目一样的方式,添加引用Microsoft.Office.Interop.Excel 组件

UI设计代码如下:

<Window x:Class="使用微软数据引擎操作Excel\_WPF.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:使用微软数据引擎操作Excel\_WPF"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><DockPanel Margin="3"><StackPanel DockPanel.Dock="Bottom"><Button x:Name="btnReadExcel" Click="btnReadExcel\_Click">Read Excel</Button></StackPanel><DataGrid x:Name="dgSource" DockPanel.Dock="Top" Margin="5"></DataGrid></DockPanel></Grid></Window>

后台完整带如下:

using System;using System.Windows;using System.Data;using System.Data.OleDb;using WForm = System.Windows.Forms;namespace 使用微软数据引擎操作Excel\_WPF{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public DataTable ReadExcel(string fileName, string fileExt){string conn = string.Empty;DataTable dtexcel = new DataTable();if (fileExt.CompareTo(".xls") == 0){//for below excel 2007 conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';";// “HDR =Yes;” 表示第一行包含列名,而不是数据。“HDR =No;” 表明相反;}else{//for above excel 2007 conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";}using (OleDbConnection con = new OleDbConnection(conn)){try{OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select \* from \[Sheet1$\]", con); //here we read data from sheet1 oleAdpt.Fill(dtexcel); //fill excel data into dataTable }catch (Exception ex){System.Windows.MessageBox.Show(ex.Message);}}return dtexcel;}private void btnReadExcel\_Click(object sender, RoutedEventArgs e){string filePath = string.Empty;string fileExt = string.Empty;WForm.OpenFileDialog file = new WForm.OpenFileDialog(); //open dialog to choose file if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user {filePath = file.FileName; //get the path of the file fileExt = System.IO.Path.GetExtension(filePath); //get the file extension if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0){try{DataTable dtExcel = new DataTable();dtExcel = ReadExcel(filePath, fileExt); //read excel file dgSource.ItemsSource = dtExcel.DefaultView;}catch (Exception ex){System.Windows.MessageBox.Show(ex.Message.ToString());}}else{System.Windows.MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning"); //custom messageBox to show error }}}}}

注意也要将项目生成平台该为 X64。

使用微软Office组件读取Excel文件相关推荐

  1. 使用Office组件读取Excel,引用Microsoft.Office.Interop.Excel出现的问题

    操作背景:asp.net操作Excel 出现问题:在本地添加引用(com):Microsoft Office 11.0 Object Library,并写好程序调试正常,部署到服务器时,出现异常 Ex ...

  2. struts1 使用poi组件 读取excel文件,创建excel ,输出excel文件

    首先要下载poi.jar 包,还有上传文件的包:commons.fileupload.jar.commons.logging.jar.commons.beanutils.jar.commons.col ...

  3. asp.net 读取excel文件的一些方法,NPOI方法

    第一种:传统方法,采用OleDB读取EXCEL文件, 优点,写法简单,老式.缺点 :服务器必须有安装此组建,而且版本必须兼容,否则读取报错,不推荐使用. private DataSet GetConn ...

  4. matlab显示服务器出现意外,Matlab 读取excel文件提示服务器出现意外情况或无法读取问题解决...

    1.问题描述: 该错误通常发生在应用函数读取excel文件(后缀xls或xlsx)时. 应用xlsread函数读取提示服务器出现意外情况: 应用importdata读取时提示can't open fi ...

  5. C# 读取EXCEL文件的三种经典方法

    1.方法一:采用OleDB读取EXCEL文件:  把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public D ...

  6. VC6.0读取Excel文件数据

    VC6.0读取Excel文件数据 文件存储在Excel文件中,因此第一步是能够在程序中方便地读取表格数据,这里用的是VC6.0 MFC.文章内容仅供参考,程序不完整. 完整的VC6.0相关程序,需要的 ...

  7. 服务器读取excel文件,关于c#:作为服务器进程读取Excel文件

    我试图找到一种适当的方法来读取NT服务器操作系统上的Excel文件的内容. 我在使用Excel API时遇到许多问题,然后在Office Automation上遇到了正式的Microsoft,它指出E ...

  8. C#读取excel文件数据丢失问题

    最近在处理C#读取excel文件时碰到了个BT问题,有部分数据读取失败了,翻看了不少资料,终于找到了问题的所在,所以在这里跟大伙分享下: 简要问题分析: 用C#读取excel文件数据时,出现数据丢失现 ...

  9. 两个关于.NET读取EXCEL文件的问题,记下来,很有用!

    今天有个同事问我个问题,他在用C#"Microsoft.Jet.OLEDB.4.0"读取EXCEL文件的时候,发现了一个问题,是这样的,他读出来的EXCEL数据在DATAGRID中 ...

最新文章

  1. js 中对象--对象结构(原型链基础解析)
  2. java读取excel2010文件_java如何读写excel2010
  3. Flume实操(一)【监控端口数据官方案例】
  4. 如何理解python_如何理解 Python
  5. 函数_月隐学python第9课
  6. 【Servlet】过滤器技术
  7. P1009 [NOIP1998 普及组] 阶乘之和-2022.02.01(python3实现)
  8. robot framework集成Jenkins环境
  9. 【Level 08】U05 Better option L6 Informative posts
  10. [区块链] 带你进入Bitcoin开发 - 环境搭建
  11. 2018上IEC计算机高级语言(C)作业 第0次作业
  12. 项目成本管理---控制成本
  13. java实现PDF转word,使用jacob插件
  14. Tomcat乱码情况完美解决
  15. Winform实现简单的记住用户名密码功能
  16. 《软件工程》第6章体系结构设计
  17. 【MySQL】exists与in的比较
  18. 联想计算机怎么设置硬盘,联想电脑硬盘模式怎么更改
  19. CorelDRAW2023安装下载教程精简版矢量绘图软件
  20. Camera 的3A

热门文章

  1. python graphx_如何使用Python/pyspark运行graphx?
  2. 如何排除网络二层环路
  3. 现代C++改变了什么
  4. 浅谈机器人基础概论--运动控制算法
  5. php 生成订单号跳号,用条码标签打印软件生成跳号的流水号
  6. 头文件 string.h cstring string 区别
  7. 全程物流可视化管理新模式
  8. 欧式距离与曼哈顿距离
  9. EZDML新版支持生成导出Markdown格式文本文档
  10. 基于opencv的四轴飞行器寻迹系统(一)——linux下opencv的安装