如何以手动和编程方式允许 excel 数据修改?

How to allow excel data modification in manual as well as programmatically?

我正在为 Excel 数据 add/update 使用 C# windows 应用程序。我添加了 Microsoft.Office.Interop.Excel 参考(参考 -> 右键单击​​ -> 添加参考 -> COM -> 类型库 -> Microsoft Excel 1X.0 对象库)。在我的表单上,我有一个面板控件 panel1、一个列表框 lstSamples 和两个按钮 btnAddSamplebtnFormatWorksheet.

我的示例代码如下:

using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;


public partial class Form1 : Form
{
    Microsoft.Office.Interop.Excel.Application excelApp;
    Workbook excelWorkBook;
    Worksheet excelWorkSheet;

    public Form1()
    {
        InitializeComponent();
        LoadExcelFile();
    }

    [DllImport("user32.dll")]
    static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

    private void LoadExcelFile()
    {
        excelApp = new Microsoft.Office.Interop.Excel.Application();

        excelApp.Visible = true;
        excelApp.ScreenUpdating = true;
        excelApp.EnableAutoComplete = false;
        excelWorkBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        IntPtr excelHwnd = new IntPtr(excelApp.Application.Hwnd);
        SetParent(excelHwnd, panel1.Handle);
    }

    private void btnAddSample_Click(object sender, EventArgs e)
    {
        excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
        int lastUsedRow = excelWorkSheet.UsedRange.Rows.Count;
        excelWorkSheet.Cells[lastUsedRow + 1, 1] = lstSamples.SelectedItem.ToString();
        lstSamples.Items.Remove(lstSamples.SelectedItem);
    }

   private void btnFormatWorksheet_Click(object sender, EventArgs e)
   {
        Range chartRange;
        excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
        chartRange = excelWorkSheet.get_Range("b2", "e9");
        chartRange.BorderAround(XlLineStyle.xlContinuous, 
        XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic, 
        XlColorIndex.xlColorIndexAutomatic);

    }
}    

请按照我提到的步骤进行操作 1. 运行 应用程序并在 "A1" 单元格(字符串类型)中添加数据 2. 再次在 "A2" 中添加一些数据单元格并按回车键 3. Select lstSamples 列表框中的一项并单击 btnAddSample(结果就像所选项目将添加到 "A3" 单元格 4. 尝试修改 "A1" 或 "A2" 单元格数据。(此处 lstSample 具有字符串类型的项目,如 Test1、Test2、Test3、....)。如果您能够编辑单元格,则单击 btnFormatWorksheet 然后尝试编辑任何单元格。

为什么要引用 COM DLL?您应该引用 .Net PIA 的 - 在此位置的主要互操作程序集,通过参考 window 中的 .Net 选项卡并浏览至:

C:\Program Files (x86)\Microsoft Visual Studio [version]\Visual Studio Tools for Office\PIA\Office[version]\Microsoft.Office.Interop.Excel.dll

您仅在单元​​测试时引用了 COM。 and how I originally worked it out。很容易混淆,因为在解决方案资源管理器中它们都被称为同一个东西!


如果这不起作用,我最初将此作为答案以节省其他人的时间被浪费。

Ahmed 和我都无法用您提供的代码重现您描述的问题。

看到我在单元格 A1 和 A2 中键入内容,然后我 select 编辑了列表中的一个项目并单击了按钮。然后我 select 单元格 A2 并键入可编辑。

ps 如果你能提供 steps 来重现,我很乐意再看一看。

更新:

您为重现问题而修改的 steps 不正确,对我有用:

更新 2:

检查消息泵过滤器是否导致焦点转到另一个 cell/control: