How do you append data to an existing Excel file? - c#

How do I append data to an already existing Excel file.
Let's say there can be a variable amount of rows already written to a file and I need to get the next row to write on.
I was thinking check for 2 blank rows and then write on the 2nd row or something like that.
How would I do this? Is there a way in EPPlus to open an Excel file and find the last line or something?

The Worksheet.Dimension should get you what you need. So if you have a sheet like this:
You can does this:
using (var package = new ExcelPackage(excelFile))
{
var ws = package.Workbook.Worksheets.First();
var lastRow = ws.Dimension.End.Row;
var lastColumn = ws.Dimension.End.Column;
Console.WriteLine($"Last Row: {lastRow}");
Console.WriteLine($"Last Column: {lastColumn}");
}
Which gives in console:
Last Row: 9
Last Column: 6

Related

How do I get closedxml.excel to recognize merged cells?

I'm trying to make a template excel file and I need to put data at various parts of the file. I have 2 fields where the data I'm importing is from a list so in the cell I do something like this:
{Item.Name}
and I of course name the range of cells that will be populated by this list. I have run into an issue where only the first record in my list will be of the correct format/ cell merge. Every record after the first completely breaks down all of my merged cells so my formatting is not good. Any ideas of how to get closedxml.excel to recognize there are merged cells?
I don't know if there is a way to get only the merged cells, but you can check if a cell is merged:
using (var excelFileStream = new FileStream("excelfile.xlsx", FileMode.Open, FileAccess.Read))
{
using IXLWorkbook workbook = new XLWorkbook(excelFileStream);
IXLWorksheet worksheet = workbook.Worksheets.Worksheet(1);
IXLCell cell = worksheet.Cell(row: 1, column: 1);
IXLRangeAddress range = cell.MergedRange().RangeAddress;
if (range.ColumnSpan > 1 || range.RowSpan > 1)
{
//merged cell
}
else
{
//non-merged cell
}
}

Find the last cell that contains data in column

I have an excel file that contains the names of the columns in the first row.
How can I find the number of the last non-empty column in the first row?
I use the library ClosedXML.Excel;
Try this:
var workbook = new XLWorkbook(fileName);
int col = workbook.Worksheet(1)
.Row(1)
.LastCellUsed()
.Address
.ColumnNumber;

Insert range of cells at the beginning of an existing excel worksheet?

I have a worksheet that has 5 rows and 3 columns. I make a copy of this sheet:
activeSheet.Copy(Type.Missing, activeSheet);
var outputSheetIndex = activeSheet.Index + 1;
var outputSheet = (Worksheet)application.Sheets[outputSheetIndex];
The above copies the sheet into another sheet. I now want to insert another range into the outputSheet and shift the outputSheet columns to the right.
I am not sure on which range object to apply the Insert method on.
I tried creating a new range to insert in the beginning, but this doesn't work:
var startCell = outputSheet.Cells[1, 1];
var endCell = outputSheet.Cells[output.Count(),
properties.Length + 1];
var writeRange = outputSheet.Range[startCell, endCell];
writeRange.Insert(XlInsertShiftDirection.xlShiftToRight);
When I insert writeRange, I want the existing range of data to be shifted to the right.
If all you want to do is insert a blank column on your new (copied worksheet), I think this would work:
outputSheet.Range["A:A"].Insert(
Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Type.Missing);
If you want the column somewhere else, you would change "A:A" to your desired range.

How do i clear rows in Excel using EPPLus library?

Right now I am providing hard code value as I know the number of rows
in excel that has data in it.I would like my program knows how to clear the excel and import new data every time in excel sheet. How do I achieve this using EPPlus v4.1.1?
My Code:*
using (ExcelPackage xlPackage = new ExcelPackage(new System.IO.FileInfo(sourcefile + fileName)))
{
ExcelWorksheet ws = xlPackage.Workbook.Worksheets[myWS];
int hardCodedRowNumber = 300;
ws.DeleteRow(2, hardCodedRowNumber);
// Other codes to import data from db after clearing excel
}
I guess the easiest and most reliable way is to delete the entire worksheet.
var oldSheet = xlPackage.Workbook.Worksheets[myWS];
xlPackage.Workbook.Worksheets.Delete(oldSheet);
var newSheet = xlPackage.Workbook.Worksheets.Add("MyNewSheet");
and from there set up line 1 from scratch.
If you strive to keep line 1 as is, you can create the new worksheet first, and copy the lines from one to the other before deleting the old worksheet:
oldSheet.Cells[1, 1, 1, oldSheet.Dimension.End.Column].Copy(newSheet.Cells[1, 1]);
Alternatively, using your own method, you can replace your "hardCodedRowNumber" with
ws.Dimension.End.Row

Insert a row in Excel using EPPlus

I do not see a way to insert a row in an existing excel file using EPPlus. I am aware of the InsertRow function but this does not insert the row at the end - similar to the insert statement in sql. If this is not possible, how would I find the last used row in an excel file.
Use following code
worksheet.Dimension.End.Row
This should give last used row info.
Here is a method that finds the last cell in a table in an Excel worksheet using EPPlus.
private ExcelRange GetLastContiguousCell(ExcelRange beginCell)
{
var worksheet = beginCell.Worksheet;
var beginCellAddress = new ExcelCellAddress(beginCell.Start.Row, beginCell.Start.Column);
var lastCellAddress = worksheet.Dimension.End;
var bottomCell = worksheet.Cells[beginCellAddress.Row, beginCellAddress.Column, lastCellAddress.Row, beginCellAddress.Column]
.First(cell => cell.Offset(1, 0).Value == null);
var rightCell = worksheet.Cells[beginCellAddress.Row, beginCellAddress.Column, beginCellAddress.Row, lastCellAddress.Column]
.First(cell => cell.Offset(0, 1).Value == null);
return worksheet.Cells[bottomCell.Start.Row, rightCell.Start.Column];
}
An important note, however, is that this assumes there are no gaps in the first row and first column. I use this method for situations where the first row is for column headings (which can't be null) and the first column is a primary Id column (which also can't be null). If your situation differs from this, you will have to adapt the method, but hopefully it will still help.
Edit
It just occurred to me that you might just be able to use worksheet.Dimension.End without all the other code. I use this more complicated method because I sometimes put other information besides the table in my worksheet, and I don't want that to be included in the calculation.

Categories