Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
35
Copy cells or Region in Excel framework
posted

Good day!

I'm not sure I chose the correct section for the question. I hope it's not a problem.

The question is this: I use the excel framework to work with files and fill in the information in them.

In my work, I need to copy the rows of tables, along with the design and formatting. For this, I created a new sheet called Template. On this sheet, I store the lines that need to be copied to the main sheet. But since the row contains merged cells, as well as the cells have different formatting. The following code does not work

ws.Rows[RowResult].CellFormat.SetFormatting(ws2.Rows[RowSource].CellFormat);

For this reason I have to act in a complicated way

In a sheet with a template, I store a sequence of numbers that tell which cells should be merged.

As example: 

1|4|4|2|1|1|1|1|2|3|3

This means that the first cell is not merged, then there are 4 merged, then 4 more, and so on.

And then I apply the following code.

private void CopyRow(Worksheet ws, Worksheet ws2, int RowSource, int RowResult, int CellsStart, int CellsStop) {
string[] map = ws2.Rows[RowSource].Cells[CellsStop + 1].Value.ToString().Split('|');
  int curPos = CellsStart;
  foreach (string s in map) {
    int c = int.Parse(s);
    if (c > 1) {
      WorksheetMergedCellsRegion r = ws.MergedCellsRegions.Add(RowResult, curPos, RowResult, curPos + (c - 1));
    }
    curPos += c;
  }
  for (int i = CellsStart; i <= CellsStop; i++) {
    ws.Rows[RowResult].Cells[i].CellFormat.SetFormatting(ws2.Rows[RowSource].Cells[i].CellFormat);
  }
}

This code is working. But very very cumbersome and heavy.

Tell me please, is it possible to somehow copy the Region together with the merged cells and their formatting?

Thank you!