简体   繁体   English

C#(WinForms)在Windows窗体应用程序中打开和编辑Excel文件

[英]C# (WinForms) open and edit excel file inside windows forms Application

I need to open view and Edit an Excel File within a Windows form. 我需要在Windows窗体中打开视图并编辑Excel文件。

I tried implementing the code for opening the Excel file in Gridview and then edit it, but that becomes too much lengthy process, hence I need to find a convenient way of View and Edit an Excel File in WindowsForms. 我尝试实现用于在Gridview中打开Excel文件然后对其进行编辑的代码,但是这变得很冗长,因此我需要找到一种方便的方法来查看和编辑WindowsForms中的Excel文件。

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks, 谢谢,

You might want to use OLEDB to read and query excel the below method returns a specific sheet in an excel file as a data table, which later you can set as Data source to your gridview. 您可能想使用OLEDB读取和查询excel,以下方法将excel文件中的特定工作表作为数据表返回,以后您可以将其设置为gridview的数据源。

    public static DataTable ConvertExcelToDataTableGroupSubGroup(string FileName)
    {

        DataTable dtResult = null;
        int totalSheet = 0; //No of sheets on excel file  
        using (OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
        {
            objConn.Open();
            OleDbCommand cmd = new OleDbCommand();
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            DataSet ds = new DataSet();
            DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string sheetName = string.Empty;
            if (dt != null)
            {
                var tempDataTable = (from dataRow in dt.AsEnumerable()
                                     where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
                                     select dataRow).CopyToDataTable();
                dt = tempDataTable;
                totalSheet = dt.Rows.Count;

                // Sheet from first index
                sheetName = dt.Rows[1]["TABLE_NAME"].ToString();
            }
            cmd.Connection = objConn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
            oleda = new OleDbDataAdapter(cmd);
            oleda.Fill(ds, "excelData");
            dtResult = ds.Tables["excelData"];
            objConn.Close();
            return dtResult; //Returning Dattable  
        }
    }

OLEDB also gives you the flexibility to write SQL queries on excel . OLEDB还使您可以灵活地在excel上编写SQL查询

First, you need to install 2 Library in NuGet 首先,您需要在NuGet中安装2 Library

  • ExcelDataReader ExcelDataReader
  • ExcelDataReader.DataSet ExcelDataReader.DataSet

https://github.com/ExcelDataReader/ExcelDataReader https://github.com/ExcelDataReader/ExcelDataReader

It can be possible read and write *.XLS, *.XLSX without Office or OLE Connection. 无需Office或OLE连接就可以读写* .XLS,*。XLSX。

And this is source what I'm using :) 这就是我正在使用的来源:)

    using ExcelDataReader;

    private DataSet ds;
    IExcelDataReader reader = null;
    OpenFileDialog openFileDialog = new OpenFileDialog();
    private void btnOpen_Click(object sender, EventArgs e)
    {
        openFileDialog.Filter = "Excel files (*.xls;*.xlsx)|*.xls;*.xlsx";
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            tbPath.Text = openFileDialog.FileName;
            var file = new FileInfo(tbPath.Text);
            try
            {
                using (var stream = new FileStream(tbPath.Text, FileMode.Open))
                {
                    if (reader != null) { reader = null; }

                    // Judge it is .xls or .xlsx
                    if (file.Extension == ".xls") { reader = ExcelReaderFactory.CreateBinaryReader(stream); }
                    else if (file.Extension == ".xlsx") { reader = ExcelReaderFactory.CreateOpenXmlReader(stream); }

                    if (reader == null) { return; }
                    ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        UseColumnDataType = true,
                        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = false,
                            ReadHeaderRow = (rowReader) => {
                                rowReader.Read();
                            },

                            // Gets or sets a callback to determine whether to include the 
                            // current row in the DataTable.
                            FilterRow = (rowReader) => {
                                return true;
                            },
                        }
                    });

                    var tablenames = GetTablenames(ds.Tables);
                    cbSheet.DataSource = tablenames;
                    listSheet.DataSource = tablenames;

                    if (cbSheet.Items.Count == 1)
                    {
                        cbSheet.SelectedIndex = 0;
                    }
                }
                cbSheet.Enabled = true;
                btnOpen.Enabled = true;
            }
            catch (Exception ex)
            {
                tbPath.Text = "";
                cbSheet.Enabled = false;
                btnOpen.Enabled = true;
                MessageBox.Show(ex.Message);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM