【问题标题】:Change Worksheet Name更改工作表名称
【发布时间】:2012-08-10 11:56:09
【问题描述】:

我正在使用 Excel Interop 创建一个 Excel 文件并向其输出数据,我想根据用户从组合框中的选择来更改工作表名称。但是,我无法从组合框获取输入以显示为工作表名称。但是,如果它来自文本框,我可以获得与工作表名称相同的值。我什至使用comboBox.SelectedItem.ToString() 并将其设为字符串,然后尝试将其应用为工作表名称。用空格替换任何非字母字符也不起作用。字符串只有字母字符和空格,但不会替换原始工作表名称。

这是我用来尝试更改工作表名称的代码。

worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value, workbook.Worksheets[sheetCount], Missing.Value, Missing.Value);
workbook.Worksheets[sheetCountPlusONe].Name = "Results " + registrationForm.selectedEvent;

【问题讨论】:

  • 你试过用comboBox.Text代替comboBox.SelectedItem.ToString()吗?
  • 是的,但它不起作用。这是 excel 互操作的一个非常令人沮丧的小怪癖

标签: c# excel excel-interop


【解决方案1】:

试试这个。我假设registrationForm 是组合框。

您必须使用GetItemText 方法分析所选项目并最终返回该项目的文本。

string WsName = this.registrationForm.GetItemText(this.registrationForm.SelectedItem);

久经考验

    private void Form1_Load(object sender, EventArgs e)
    {
        this.comboBox1.Items.Add("Sheet1111");
        this.comboBox1.Items.Add("Sheet2222");
        this.comboBox1.Items.Add("Sheet3333");
    }

   private void btnOPen_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();

        xlexcel.Visible = true;

        //~~> Open a File
        xlWorkBook = xlexcel.Workbooks.Open("C:\\sample.xlsx", 0, true, 5, "", "", true,
        Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        // Set Sheet 1 as the sheet you want to work with
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        string WsName = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);

        xlWorkSheet.Name = WsName;

       //
       //~~> Rest of code
       //
    }

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2018-08-17
    • 1970-01-01
    相关资源
    最近更新 更多