C#:Copy protected worksheet to another excel file

2019-09-06 15:43发布

I was trying to copy paste one protected worksheet to another excel file but i`m getting error like

"Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))"

C# Code:

try
{
    string startPath = System.IO.Path.GetDirectoryName(
        System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
    string filePath = System.IO.Path.Combine(startPath, strPath);

    wBook = xCel.Workbooks.Open(filePath);
    wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);
    wSheet.Copy(Type.Missing, Type.Missing);
    wSheet = (Excel.Worksheet)xlApp.Workbooks[0].ActiveSheet;
    //wSheet = (Excel.Worksheet)xlApp.Workbooks[1].Sheets[1];
}
finally
{
    if (wBook != null)
    {
        wBook.Close();
    }
    if (xlApp != null)
    {
        xlApp.Quit();
    }                
}

Could somebody tel what wrong i`m doing here???

OR

Please tell me if there are any better ways to do this??

Thanks.

1条回答
爷的心禁止访问
2楼-- · 2019-09-06 15:52

I would check:

wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);

or

wSheet = (Excel.Worksheet)xlApp.Workbooks[0].ActiveSheet;

Your error seems to suggest either the wBook or the xlApp has no values in it. This is why the index would be invalid (well rather the workbooks or worksheets are empty. I think)

If it is a protected worksheet, wouldn't the fact its protected stop you copying it?

查看更多
登录 后发表回答