1. 程式人生 > >C# 開啟Excel檔案方法

C# 開啟Excel檔案方法

一、C#怎樣開啟Excel檔案

1.右鍵–Add DevExpress Item – New Item,新建一個Form窗體

2.開啟工具箱,搜尋spreadsheetControl

3.將工具spreadsheetControl拖入新建的窗體中

4.可新增開啟,儲存,列印等按鈕,我是隨窗體開啟一起開啟excel,所以沒有新增按鈕,主要程式碼如下:

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.點選某個按鈕彈出frmARFCN的form窗體

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

6.顯示效果如下