【发布时间】:2021-06-06 05:40:17
【问题描述】:
试图让旧的 VB.NET 应用程序再次运行。一个功能是构建一个由 Tab/Return 字符分隔的文本组成的文本字符串,然后(通过互操作)创建一个 Excel 工作簿,添加一个工作表,然后(希望)将文本字符串粘贴到工作表中。
代码如下:
Private Function AddNewWorksheetToWorkbook(
ByVal theWorkbook As Workbook,
ByVal worksheetName As String,
ByVal textToPaste As String
) As Microsoft.Office.Interop.Excel.Worksheet
Dim newWorksheet As Microsoft.Office.Interop.Excel.Worksheet
newWorksheet = theWorkbook.Worksheets.Add()
newWorksheet.Name = worksheetName
theWorkbook.Save()
newWorksheet.Activate() 'All works fine, file saved, worksheet named and Active as desired
Dim app As Microsoft.Office.Interop.Excel.Application
app = newWorksheet.Application
If app.ActiveSheet.Name = newWorksheet.Name Then 'Just a test to make sure ActiveSheet is the one desired -- it is
Clipboard.SetText(textToPaste) 'Clipboard has text delimited by vbTab and vbReturn (a "plain" text table)
newWorksheet.Range("A1").Select() 'Cell "A1" is properly selected
newWorksheet.Paste() 'BOOM! Get System.Runtime.InteropServices.COMException: 'Microsoft Excel cannot paste the data.'
End If
theWorkbook.Save()
Return newWorksheet
End Function
正如 cmets 中所述,在调用 Worksheet.Paste() 方法之前一切顺利。
我尝试了Paste() 和PasteSpecial() 等的变体。不高兴。
不断收到 System.Runtime.InteropServices.COMException: 'Microsoft Excel 无法粘贴数据。'
我能够(手动,而不是通过互操作)在 Excel 中单击“粘贴”,它工作得很好。
感谢 stackoverflow 社区提供的任何见解!
【问题讨论】:
-
做一个小测试。从头开始:
dim excelApp = new excel.Application() with { .DisplayAlerts = false, .Visible = true } dim wBook = excelApp.Workbooks.Add(Type.Missing) dim sheet as excel.Worksheet = wBook.Worksheets.Add() Clipboard.SetText(textToPaste, TextDataFormat.Text) sheet.Paste()。它有效吗?不?那么这就是您要粘贴的内容不兼容。 -
excel是Imports excel = Microsoft.Office.Interop.Excel。 -- 在TaskManager中,杀死所有你之前留下的EXCEL.EXE进程。 -
我不会太难将该字符串放入 DataTable 中。调查 GemBox 以便轻松导入。
-
感谢@Jimi。我确认剪贴板有效载荷不是问题。 Worksheet.Paste() 互操作似乎有问题,我选择遵循此处建议的解决方案 link。我很快就会在下面发布我的解决方案。
标签: excel vb.net interop clipboard paste