使用微软Office组件读取Excel文件

有些时候不想使用第三方组件来操作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。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MFC(Microsoft Foundation Classes)是微软提供的用于开发 Windows 应用程序的一套类库。如果想要利用MFC读取Excel文件中的图片,可以按照以下步骤进行操作: 1. 在MFC应用程序中添加对Excel的支持。可以使用Microsoft Excel COM组件进行操作,通过引用"Microsoft Excel xx.x Object Library",使用Excel的对象模型进行操作。 2. 使用MFC打开Excel文件使用COleVariant对象创建Excel应用程序对象,并使用CreateDispatch()方法创建Excel应用程序的实例,然后通过调用相关方法打开Excel文件。 3. 获取工作表对象和图片对象。通过调用Application对象的Worksheets属性获取工作表对象,然后使用工作表对象的Shapes属性获取所有的形状对象(包括图片)。 4. 遍历形状对象列表,判断每个形状对象是否为图片。可以通过形状对象的Type属性判断其类型是否为图片。 5. 如果形状对象为图片类型,可以使用Shape对象的CopyPicture()方法将图片复制到剪贴板中。 6. 将图片从剪贴板中读取到MFC应用程序中。可以使用COleDataObject类和COleDataSource类进行剪贴板数据的传输。可以使用OleGetClipboard函数获取剪贴板中的数据。 7. 完成图片的读取后,记得清理资源。关闭Excel文件、释放Excel应用程序对象等。 需要注意的是,在使用MFC读取Excel图片时,需要确保已经安装了Microsoft Office,同时需要根据Excel文件的格式、版本以及需求进行适当的调整和处理。 以上是关于如何使用MFC读取Excel图片的一般步骤和思路,具体实现可能会根据实际情况有所差异,可根据具体需求进行相应的调整和编码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值