usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Text.RegularExpressions;usingDocumentFormat.OpenXml;usingDocumentFormat.OpenXml.Packaging;usingDocumentFormat.OpenXml.Spreadsheet;namespaceOpenXMLSDK_Sample12{classProgram{staticvoidMain(string[]args){conststringFILE=@"C:\Users\Public\Documents\openxmlsdk19.xlsx";conststringSHEET_NAME="Sheet1";using(SpreadsheetDocumentexcelDoc=SpreadsheetDocument.Open(FILE,true)){WorkbookPartbookPart=excelDoc.WorkbookPart;intsheet_index=GetWorksheetIndex(bookPart,SHEET_NAME);WorksheetPartsheet_part=GetWorksheetPart(bookPart,sheet_index);InsertRows(sheet_part,3,1);InsertRows(sheet_part,5,2);InsertRows(sheet_part,8,3);}//ファイルを開くSystem.Diagnostics.Process.Start(FILE);}publicstaticvoidInsertRows(WorksheetPartws_part,uintrow_number_at,uintnew_row_count=1){if(row_number_at==0){thrownewException("row_number_at must be positive");}if(new_row_count<=0){thrownewException("new_row_count must be positive");}SheetDatasheet_data_part=ws_part.Worksheet.GetFirstChild<SheetData>();Regexregex=newRegex(@"\$?[A-Za-z]+\$?[1-9][0-9]*",RegexOptions.IgnoreCase);//セル番地にマッチ/*** dimension ***/SheetDimensiondimension_modified=ws_part.Worksheet.GetFirstChild<SheetDimension>();if(isRangeAddress(dimension_modified.Reference)){stringlast_cell_address=dimension_modified.Reference.Value.Split(':')[1];if(row_number_at<=GetRowIndex(last_cell_address)){dimension_modified.Reference=newStringValue(ShiftedRangeOnInsertRow(dimension_modified.Reference,row_number_at,new_row_count));}else{return;}}else{return;}/*** Cell Merge ***/MergeCellsmergeCells=ws_part.Worksheet.GetFirstChild<MergeCells>();if(mergeCells!=null){foreach(MergeCellmerge_cellinmergeCells){merge_cell.Reference=ShiftedRangeOnInsertRow(merge_cell.Reference,row_number_at,new_row_count);}}/*** Shift Row and Cell Reference ***/foreach(varrowinsheet_data_part.Elements<Row>().Where(r=>r.RowIndex>=row_number_at)){row.RowIndex+=new_row_count;foreach(varcellinrow.Elements<Cell>()){cell.CellReference=$"{GetColumnName(cell.CellReference)}{row.RowIndex}";}}/*** Shift Formula Reference ***/foreach(varcellinsheet_data_part.Descendants<Cell>().Where(c=>c.CellFormula!=null)){/*** Shift Formula ***/stringformula=cell.CellFormula.Text;if(!string.IsNullOrEmpty(formula)){cell.CellFormula.Text=ShiftedRangeOnInsertRow(formula,row_number_at,new_row_count);}/*** Shift Formula Reference Attribute ***/stringreference=cell.CellFormula.Reference;if(!string.IsNullOrEmpty(reference)){cell.CellFormula.Reference=ShiftedRangeOnInsertRow(cell.CellFormula.Reference,row_number_at,new_row_count);}}/*** CalcChain ***/WorkbookPartwb_part=ws_part.GetParentParts().ElementAt(0)asWorkbookPart;Sheetssheets=wb_part.RootElement.Elements<Sheets>().First();stringsheet_part_id=wb_part.GetIdOfPart(ws_part);stringsheet_id=(sheets.First(sh=>(shasSheet).Id==sheet_part_id)asSheet).SheetId;CalculationChainPartcalc_chain_part=wb_part.GetPartsOfType<CalculationChainPart>().FirstOrDefault();if(calc_chain_part!=null){foreach(CalculationCellcellincalc_chain_part.CalculationChain.Elements<CalculationCell>().Where(c=>c.SheetId==sheet_id)){cell.CellReference=ShiftedRangeOnInsertRow(cell.CellReference,row_number_at,new_row_count);}}/*** name definition ***//*** graph ***//*** pivot table & graph ***//*** Add new Cell and Copy cell style from the previous row ***/varrow_previous=sheet_data_part.Elements<Row>().FirstOrDefault(r=>r.RowIndex==row_number_at-1);SheetDimensiondimension=ws_part.Worksheet.GetFirstChild<SheetDimension>();uint[]col_range;if(row_previous==null){col_range=dimension.Reference.Value.Split(':').Select(s=>GetColumnIndex(s)).ToArray();}else{col_range=row_previous.Spans.InnerText.Split(':').Select(s=>Convert.ToUInt32(s)).ToArray();}for(uinti=0;i<new_row_count;i++){varrow_new=newRow();if(row_previous!=null){foreach(varattrinrow_previous.GetAttributes()){row_new.SetAttribute(newOpenXmlAttribute(){LocalName=attr.LocalName,NamespaceUri=attr.NamespaceUri,Prefix=attr.Prefix,Value=attr.Value});}}row_new.RowIndex=row_number_at+i;for(uintj=col_range[0];j<=col_range[1];j++){Cellnew_cell=newCell(){CellReference=$"{GetColumnName(j)}{row_new.RowIndex}"};if(row_previous!=null){Cellprevious_cell=GetCell(ws_part,$"{GetColumnName(j)}{row_number_at - 1}");new_cell.StyleIndex=previous_cell.StyleIndex;}row_new.Append(new_cell);}sheet_data_part.InsertAt<Row>(row_new,(int)row_new.RowIndex.Value-1);}}publicstaticstringShiftedRangeOnInsertRow(stringrange,uintrow_number_at,uintnew_row_count){Regexregex=newRegex(@"\$?[A-Za-z]+\$?[1-9][0-9]*",RegexOptions.IgnoreCase);//セル番地にマッチstringrange_shifted=range;MatchCollectionmc=regex.Matches(range);for(inti=mc.Count-1;i>=0;i--){stringrange_element_address=mc[i].ToString();if(GetRowIndex(range_element_address)>=row_number_at){range_shifted=range_shifted.Replace(range_element_address,getOffsetAddress(range_element_address,(int)new_row_count,0));}}returnrange_shifted;}publicstaticstringgetOffsetAddress(stringsource_cell_address,intbiasRow,intbiasColumn){if(string.IsNullOrEmpty(source_cell_address)||!isOneCellAddress(source_cell_address)){returnstring.Empty;}longoffset_address_row=GetRowIndex(source_cell_address)+biasRow;if(offset_address_row<1){offset_address_row=1;}if(offset_address_row>MAX_ROW_INDEX){offset_address_row=MAX_ROW_INDEX;}longoffset_address_col=GetColumnIndex(source_cell_address)+biasColumn;if(offset_address_col<1){offset_address_col=1;}if(offset_address_col>MAX_COL_INDEX){offset_address_col=MAX_COL_INDEX;}//absolute addressstringcol_name=GetColumnName((uint)offset_address_col);if(source_cell_address.StartsWith("$")){col_name=$"${col_name}";}stringrow_number=offset_address_row.ToString();if(source_cell_address.LastIndexOf('$')>0){row_number=$"${row_number}";}//return GetColumnName((uint)offset_address_col) + offset_address_row;return$"{col_name}{row_number}";}//以下省略}}
/*** Add new Cell and Copy cell style from the previous row ***/varrow_previous=sheet_data_part.Elements>Row<().FirstOrDefault(r=>r.RowIndex==row_number_at-1);SheetDimensiondimension=ws_part.Worksheet.GetFirstChild>SheetDimension<();uint[]col_range;if(row_previous==null){col_range=dimension.Reference.Value.Split(':').Select(s=>GetColumnIndex(s)).ToArray();}else{col_range=row_previous.Spans.InnerText.Split(':').Select(s=>Convert.ToUInt32(s)).ToArray();}for(uinti=0;i<new_row_count;i++){varrow_new=newRow();if(row_previous!=null){foreach(varattrinrow_previous.GetAttributes()){row_new.SetAttribute(newOpenXmlAttribute(){LocalName=attr.LocalName,NamespaceUri=attr.NamespaceUri,Prefix=attr.Prefix,Value=attr.Value});}}row_new.RowIndex=row_number_at+i;for(uintj=col_range[0];j<=col_range[1];j++){Cellnew_cell=newCell(){CellReference=$"{GetColumnName(j)}{row_new.RowIndex}"};if(row_previous!=null){Cellprevious_cell=GetCell(ws_part,$"{GetColumnName(j)}{row_number_at - 1}");new_cell.StyleIndex=previous_cell.StyleIndex;}row_new.Append(new_cell);}sheet_data_part.InsertAt<Row>(row_new,(int)row_new.RowIndex.Value-1);}