我从一个工作簿中复制工作表并将其粘贴到第二个工作簿中。 我使用这段代码:
book = appExcel.Workbooks.Open(@"e:\tr\pliki\filename.xlsm",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
Microsoft.Office.Interop.Excel.Global global = new Microsoft.Office.Interop.Excel.GlobalClass();
sheet.Copy(Missing.Value, global.Sheets[5]);
book.Save();
一切正常,但问题在于公式。在工作表复制后,公式中的公式引用第一个工作簿中的值。公式路径包含复制它的第一个工作簿的路径:
='E:\tr\pliki\[filename.xlsm]worksheetA'!A1:E2
应该是这样的:
='worksheet'!A1:E2
有人帮助我吗?
答案 0 :(得分:2)
我不知道干净的方式来做你想做的事情,无论如何这是一个可以解决你的问题的解决方法。这只是在复制工作表之前将公式更改为文本并在此之后恢复所有内容的问题。即您可以使用您知道数据中不存在的某些字符串替换单元格中的所有=(例如,像X_X_X_X_X_X这样奇怪的东西),然后恢复到初始状态。
代码可能是这样的:
Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook srcBook = appExcel.Workbooks.Open(@"c:\tmp\test.xls",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
Microsoft.Office.Interop.Excel.Workbook destBook = appExcel.Workbooks.Add(Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet srcSheet = (Microsoft.Office.Interop.Excel.Worksheet)srcBook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range usedRange = srcSheet.UsedRange;
usedRange.Replace("=", "X_X_X_X_X_X", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
srcSheet.Copy(destBook.Worksheets[1], Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet destSheet = (Microsoft.Office.Interop.Excel.Worksheet)destBook.Worksheets[1];
usedRange.Replace("X_X_X_X_X_X", "=", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
usedRange = destSheet.UsedRange;
usedRange.Replace("X_X_X_X_X_X", "=", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);