简体   繁体   中英

excel cell coloring

I am using c# to color particular cells of excel file. i am using

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(destPath);
 Worksheet ws = wb.Worksheets[1];
ws.Cells[row, clmn].Interior.Color = XlRgbColor.rgbBlack;

to color cells..But this is not working.. It is giving an exception on the last line where i am coloring the cells

"Exception from HRESULT: 0x800A03EC"

I am unable to fix the exception Can anyone help me out..

It might not work because the worksheet is protected.

You can check it the following way:

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(destPath);
Worksheet ws = wb.Worksheets[1];

bool wasProtected = ws.ProtectContents;
if (wasProtected == true)
{
    // unprotect the worksheet
}
else
{
    ws.Cells[row, clmn].Interior.Color = XlRgbColor.rgbBlack;
}

...

if (wasProtected == true)
{
    // protect back the worksheet
}

In my previous project I used the following snippet to Color Cells in Excel:

ws.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToWin32(Color.Black);

I tested the code that you have on a new Excel file and it works fine. However, I was able to reproduce the error when testing with a row value of 0. So maybe the problem is with the row and clmn values. Otherwise it must be something specific to your Excel file... maybe a protected cell or something along those lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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