簡體   English   中英

使用 C# 在 Windows 窗體應用程序中創建 Excel 文件

[英]Creating Excel file in Windows Forms application using C#

我想問一下如何創建一個新的Excel文件。 我正在編寫一個程序,有一個部分我不知道如何去做。

我有一個按鈕可以創建新的 Excel 文件,所以你點擊它,它會打開文件對話框,然后將它保存在某個地方。 但我不知道怎么做,我已經嘗試了數百個視頻和頁面,但我就是想不通。

你能告訴我它是如何完成的嗎? 謝謝

您可以嘗試使用Microsoft.Office.Interop.Excel 使用前,請確保已安裝Excel。

以下是如何使用它的步驟。

首先,從 Nuget 安裝Microsoft.Office.Interop.Excel包。

在此處輸入圖片說明

然后,參考下面的演示代碼。

private void button1_Click(object sender, EventArgs e)
{
    object Nothing = System.Reflection.Missing.Value;
    var app = new Microsoft.Office.Interop.Excel.Application();
    app.Visible = false;
    Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Add(Nothing);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[1];
    worksheet.Name = "WorkSheet";
    // Write data
    worksheet.Cells[1, 1] = "FileName";
    worksheet.Cells[1, 2] = "FindString";
    worksheet.Cells[1, 3] = "ReplaceString";

    // Show save file dialog
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        worksheet.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
        workBook.Close(false, Type.Missing, Type.Missing);
        app.Quit();
    }
}

您可以使用 Spire.XLS 庫在 windows 窗體應用程序中創建 Excel。

首先,通過 NuGet 為 .NET 庫搜索並安裝 Spire.XLS。

其次,參考下面的示例代碼用它創建 Excel。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Spire.Xls;

namespace CreateExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Range["A3"].Text = "Hello World";
            workbook.SaveToFile("Sample.xlsx", ExcelVersion.Version2013);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM