I am trying to achieve the following in an Excel VSTO add-in:
Copying/applying cell formatting from the original version of an Excel file.
Reason: while processing Excel files, we occasionally need to change the style/coloring of a file in order to be able to process certain cells only. After the file has been processed, we need to restore the original cell formats. For that purpose, I wrote a VSTO add-in.
It reads the orignal file, iterates over all used cells and applies the formatting of each to the respective cell (address) in the final file. It works fine, but it opens the original file via Interop - which can be a problem because the file name does not change. Also: not ideal performance-wise. Also: the user sees the original file during the operation which can cause confusion.
Therefore I would like to "open" the original file via ClosedXml. This is where I get stuck:
var xl = Globals.ThisAddIn.Application;
var dest = xl.ActiveWorkbook; //Interop
try
{
var org = new XLWorkbook(pfad); //ClosedXml
foreach (IXLWorksheet sheet in org.Worksheets)
{
var used = sheet.RangeUsed(true);
Excel.Worksheet dsheet = dest.Sheets[sheet.Name];
foreach (IXLCell cel in used.Cells(false))
{
var adr = cel.Address;
var interior = dsheet.Range[adr].Interior;
interior.Color = cel.Style.Fill.BackgroundColor;
interior.Pattern = cel.Style.Fill.PatternColor;
//Crash!
//HRESULT: 0x800A03EC
//...
//...
var borders = dsheet.Range[adr].Borders;
var orgbord = cel.Style.Border;
borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = orgbord.TopBorder;
//Crash!
//HRESULT: 0x800A03EC
//...
//...
}
}
org.Dispose();
}
catch (Exception ex)
{
log.WriteLine(ex.Message);
}
I think the trouble is that in Excel interop, things like Color/TintAndShade etc. as well as borders linestyle/Weight etc. are much more granularly defined than in ClosedXml which makes the two kind of incompatible?
Has anyone here tried something similar before and knows how to do this?
Would be great if I could somehow solve this so I'm not stuck with all interop.