c# - Merge adjacent cells in excel using openxml -
i wan tto merge 5 adjacent cells in excel using openxml.i tried modification on following code snippet adding 1 more cell not working.it working 2 cells . shall if want merge more tow cells
// given document name, worksheet name, , names of 2 adjacent cells, merges 2 cells. // when 2 cells merged, content 1 cell preserved: // upper-left cell left-to-right languages or upper-right cell right-to-left languages. private static void mergetwocells(worksheet worksheet, string cell1name, string cell2name) { // open document editing. // verify if specified cells exist, , if not exist, create them. //createspreadsheetcellifnotexist(worksheet, cell1name); //createspreadsheetcellifnotexist(worksheet, cell2name); mergecells mergecells; if (worksheet.elements<mergecells>().count() > 0) { mergecells = worksheet.elements<mergecells>().first(); } else { mergecells = new mergecells(); // insert mergecells object specified position. if (worksheet.elements<customsheetview>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<customsheetview>().first()); } else if (worksheet.elements<dataconsolidate>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<dataconsolidate>().first()); } else if (worksheet.elements<sortstate>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<sortstate>().first()); } else if (worksheet.elements<autofilter>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<autofilter>().first()); } else if (worksheet.elements<scenarios>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<scenarios>().first()); } else if (worksheet.elements<protectedranges>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<protectedranges>().first()); } else if (worksheet.elements<sheetprotection>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<sheetprotection>().first()); } else if (worksheet.elements<sheetcalculationproperties>().count() > 0) { worksheet.insertafter(mergecells, worksheet.elements<sheetcalculationproperties>().first()); } else { worksheet.insertafter(mergecells, worksheet.elements<sheetdata>().first()); } } // create merged cell , append mergecells collection. string s1 = cell1name + ":" + cell2name ; mergecell mergecell = new mergecell() { reference = s1 }; mergecells.append(mergecell); worksheet.save(); }
you don't need alter code. if want merge multiple cells, ensure cell1name top-left cell of cells want merge , cell2name bottom-right cell (i.e. a1:b2 merge cells a1,a2,b1, , b2).
also, value in top-left cell preserved (or top-right right-to-left text).
Comments
Post a Comment