Skip to content

Instantly share code, notes, and snippets.

@josephmate
Created June 8, 2021 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephmate/71379497991e4ac7e59625d7f4190d79 to your computer and use it in GitHub Desktop.
Save josephmate/71379497991e4ac7e59625d7f4190d79 to your computer and use it in GitHub Desktop.
OpenXML DeleteRows Sample
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace OpenXMLTest
{
class Program2
{
static void Main(string[] args)
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open("C:\\Users\\Joseph\\Desktop\\Price History.xlsx", true))
{
/*
* name: Sheet1
sheetId: 1
state: visible
id: rId3
name: Sheet2
sheetId: 2
state: visible
id: rId4
*/
Sheet sheet1 = (Sheet)spreadsheetDocument.WorkbookPart.Workbook.Sheets.Where(
i => i.GetAttributes().Where(attr => attr.LocalName == "name").FirstOrDefault().Value == "Sheet1").FirstOrDefault();
Console.WriteLine(sheet1.GetAttributes().Where(attr => attr.LocalName == "name").FirstOrDefault().Value);
string sheet1Id = sheet1.Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet1Id);
List<Row> rows = worksheetPart.Worksheet.GetFirstChild<SheetData>()
.Elements<Row>()
.Skip(1)
.ToList();
uint currentRowIdx = 2;
foreach(Row row in rows)
{
Console.WriteLine("Original Row Index: " + row.RowIndex);
row.RowIndex.Value = currentRowIdx;
List<Cell> cells = row.Elements<Cell>().ToList();
// https://stackoverflow.com/questions/49109203/how-to-remove-row-from-excel-using-openxml
foreach (Cell cell in cells)
{
// remove the digits from the end of the string
// Example : A123 becomes A
string columnLetterId = Regex.Replace(cell.CellReference.Value, @"[\d-]", "");
cell.CellReference.Value = $"{columnLetterId}{currentRowIdx}";
Console.WriteLine(cell.CellReference.Value);
}
Console.WriteLine("New Row Index: " + row.RowIndex);
if (cells.Count >= 3)
{
Cell priceCell = cells[2];
if (priceCell == null || priceCell.CellValue == null || Double.Parse(priceCell.CellValue.Text) > 2.0)
{
row.Remove();
} else
{
currentRowIdx++;
}
} else
{
currentRowIdx++;
}
}
spreadsheetDocument.Save();
}
Console.WriteLine("Done");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment