繁体   English   中英

如何从c# winform复制数据粘贴到Excel Worksheet

[英]How to copy data from c# winform and paste into Excel Worksheet

我正在开发一个允许用户从数据库中提取零件号的程序。 然后将零件号粘贴到有效的 Excel 表中。

我正在尝试使用 Excel 互操作 Excel 16.0 来执行此操作。 我可以复制数据,但在将其粘贴到 excel 时遇到问题。

private void cmdCopyToExcel_Click(object sender, EventArgs e)
    {
        string wb = cmb_BookName.Text.ToString();
        string ws = cmb_SheetName.Text.ToString();

        if (chkContainer.Checked)
        {
            Excel.Application xlApp = new Excel.Application();

            Excel.Workbook xlWorkbook = xlApp.Workbooks[wb];                      
            Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[ws];
            
            xlWorksheet.Cells[48, 4] = cboContainer.Text;              
        }

我能够获得我需要的打开的 excel 工作簿和工作表,但是当我尝试将其粘贴到 excel 时,我得到的只是一个 COM 异常。 异常发生在第 10 行。我试过使用 ("wb name") 和 ("ws name"),也尝试过使用索引号 [1] 用于工作簿,使用索引号 [3] 用于工作表,但没有任何效果。

谁能看到我做错了什么,或者有更简单的方法从 C# 复制并粘贴到 excel 单元格中吗?

添加:我试着打开我想添加测试的工作簿,只是想看看我是否能让它工作。

这是代码:

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            //create a instance for the Excel object  
            Excel.Application oExcel = new Excel.Application();

            //specify the file name where its actually exist  
            string filepath = @"K:\R&D Dept\Development Lab\R&D Test Request System (For testing and training)\Test Matrices\JRD Test Matrix for part numbers.xlsm";

            //pass that to workbook object  
            Excel.Workbook WB = oExcel.Workbooks.Open(filepath);

            // statement get the workbookname  
            string ExcelWorkbookname = WB.Name;

            // statement get the worksheet count  
            int worksheetcount = WB.Worksheets.Count;

            Excel.Worksheet wks = (Excel.Worksheet)WB.Worksheets[3];

            // statement get the firstworksheetname  

            string firstworksheetname = wks.Name;

            //statement get the first cell value  
            var firstcellvalue = ((Excel.Range)wks.Cells[48, 4]).Value;
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
    }
}

}

这行得通,所以我想我的问题变成了如何使用已经打开的 Excel 工作簿和工作表?

我将从获取一系列单元格开始:即{ Range test = {yourWorksheet}.Cells[RowNumber, ColumnNumber] }

一旦你有了它,你可以通过调用 value 或 value2 属性来设置该单元格的值,如下所示:{ test.Value or test.Value2 = {yourPastedData} }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM