How to open Excel file in C#

1. How to open an Excel file in C#

1. Right-click – Add DevExpress Item – New Item, create a new Form form

2. Open the toolbox and search for spreadsheetControl

3. Drag the tool spreadsheetControl into the new form

4. Buttons such as open, save and print can be added. I opened excel along with the form opening, so no button was added. The main code is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using DevExpress.Spreadsheet;

namespace rdms.Forms
{
public partial class frmARFCN : Form
{
    private static log4net.ILog LOG = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    //记录窗体的名称
    readonly string mainFormText;

    public frmARFCN()
    {
        InitializeComponent();

        //记录窗体的名称,并实现文档变化事件的处理,方便显示新的文件名称
        mainFormText = this.Text;
        this.spreadsheetControl1.DocumentLoaded += new EventHandler(spreadsheetControl1_DocumentLoaded);
        openFile();
    }

    /// <summary>
    /// 文档变化后,实现对新文件名称的显示
    /// </summary>
    void spreadsheetControl1_DocumentLoaded(object sender, EventArgs e)
    {
        string fileName = Path.GetFileName(this.spreadsheetControl1.Document.Path);
        if (String.IsNullOrEmpty(fileName))
        {
            Text = mainFormText;
        }
        else
        {
            Text = fileName + " - " + mainFormText;
        }
    }

    /// <summary>
    /// 打开Excel文件
    /// </summary>
    private void openFile()
    {
        string path = Application.StartupPath;
        LOG.Info("path==="+path);
        string filePath = path + "\\Data\\about.xls";
        if (!string.IsNullOrEmpty(filePath))
        {
            IWorkbook workbook = spreadsheetControl1.Document;
            workbook.LoadDocument(filePath);
        }
    }

    /// <summary>
    /// 保存Excel文件
    /// </summary>
    private void btnSaveFile_Click(object sender, EventArgs e)
    {
        spreadsheetControl1.SaveDocument();
    }

    /// <summary>
    /// Excel文件打印
    /// </summary>
    private void btnPreview_Click(object sender, EventArgs e)
    {
        this.spreadsheetControl1.ShowPrintPreview();
    }
}
}

5. Click a button to pop up the frmARFCN form form

 private void btn_Click(object sender, EventArgs e)
{        
    using (frmARFCN frm = new frmARFCN())
    {
        DialogResult ret = frm.ShowDialog(this);
    }       
}

6. The display effect is as follows

For more blog content, please refer to my blog Wang's Blog

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647301&siteId=291194637