I'm using EPPlus to manipulate an Excel file. I need to insert a formula that references an entire column. I'm currently using:
currentWorksheet.Cells[2, 4].Formula = "QUARTILE(C:C,1)";
If I manually enter this formula into the Excel sheet it works, or if I insert it with a finite range in EPPlus like so:
=QUARTILE(C2:C1000,1)
But when it's inserted as a whole column range of C:C using EPPlus it results in the following:
=QUARTILE(#REF!,1)
Is there something special needed when referencing entire columns, or is this just a bug in EPPlus?
You can use following code
worksheet.Cells["A1"].Formula= "=QUARTILE(C2:C1000,1)";
Stewart is correct in that the formula should be valid. Try pasting in the rest of your code. I thought together a quick unit test and it worked fine:
[TestMethod]
public void Quartile_Range_Test()
{
//Throw in some data
var dtMain = new DataTable("tblData");
dtMain.Columns.Add(new DataColumn("Col1", typeof(int)));
for (var i = 0; i < 20; i++)
{
var row = dtMain.NewRow();
row["Col1"] = i * 100;
dtMain.Rows.Add(row);
}
//Clear the file
var newFile = new FileInfo(#"C:\Temp\Temp.xlsx");
if (newFile.Exists)
newFile.Delete();
using (var package = new ExcelPackage(newFile))
{
var currentWorksheet = package.Workbook.Worksheets.Add("Test");
currentWorksheet.Cells["C1"].LoadFromDataTable(dtMain, false);
currentWorksheet.Cells[2, 4].Formula = "QUARTILE(C:C,1)";
package.Save();
}
}
Related
I am using Epplus to copy a worksheet from a wokbook and paste it in another workbook.I can able to copy the worksheet sucesssfully,by using the below code.
ExcelPackage masterPackage = new ExcelPackage(new FileInfo(#"C:\\Users\\350154\\Desktop\\vb workouts\\testsample.xlsx"));
ExcelPackage pckg = new ExcelPackage(new FileInfo("C:\\Users\\350154\\Desktop\\vb workouts\\as.xlsx"));
string workSheetName = pckg.Workbook.Worksheets[1].Name;
ExcelWorksheet pck = pckg.Workbook.Worksheets[1];
pck.ConditionalFormatting.RemoveAll();
masterPackage.Workbook.Worksheets.Add(workSheetName, pck);
The code copies the sheet sucessfully.But the copied sheet has formulas in their cells.So Values not copying in a new excel pls help me to solve this.
If you're just looking to copy the values from one spreadsheet into a new sheet in another, try this:
public static void CopySheetValues(string sourcePath, string sheetName, string destPath)
{
using (var src = new ExcelPackage(new FileInfo(sourcePath)))
using (var dest = new ExcelPackage(new FileInfo(destPath)))
{
var wsSrc = src.Workbook.Worksheets[sheetName];
var wsDest = dest.Workbook.Worksheets[wsSrc.Name] ?? dest.Workbook.Worksheets.Add(wsSrc.Name);
for (var r = 1; r <= wsSrc.Dimension.Rows; r++)
{
for (var c = 1; c <= wsSrc.Dimension.Columns; c++)
{
var cellSrc = wsSrc.Cells[r, c];
var cellDest = wsDest.Cells[r, c];
// Copy value
cellDest.Value = cellSrc.Value;
// Copy cell properties
cellDest.Style.Numberformat = cellSrc.Style.Numberformat;
cellDest.Style.Font.Bold = cellSrc.Style.Font.Bold;
// TODO... Add any additional properties that you may want to copy over
}
}
dest.Save();
}
}
UPDATE: Sample code updated to show how formatting can also be copied from the source to the destination worksheet
Thanks #Pete. But I found a way to copy an entire worksheet to another workbook while I was looking for a different issue. https://github.com/JanKallman/EPPlus/issues/94
You change the below line to add the worksheet to the workbook.
var wsDest = m_GeneratedHeader.Workbook.Worksheets[wsSrc.Name] ?? m_GeneratedHeader.Workbook.Worksheets.Add(wsSrc.Name, wsSrc);
No need to use the two 'for' loops to iterate through rows and columns to copy each property. Adding the worksheet will copy cell style, font style, merge cells, etc... Worked for me.
Note that this was introduced after EPPlus 4.5.0.1
I have been stuck with this problem for a while and cannot seem to find a way around it. I have read numerous articles on Stack Overflow yet nothing seems to answer my question. The tutorials I have followed as well all give different solutions but none seem to work.
I am trying to write data from a DataTable into an excel spreadsheet. I am using Microsoft.Office.Interop.Excel package and I do have Excel installed on my pc with admin rights.
At the top of my console app I have the following:
using Microsoft.Office.Interop.Excel;
I am using the following code to create the excel spreadsheet and populate it where dt is the DataTable:
var excel = new Application();
excel.Visible = false;
excel.DisplayAlerts = false;
var workBook = (Workbook)excel.Workbooks.Add(Type.Missing);
var workSheet = (Worksheet)workBook.ActiveSheet;
workSheet.Name = "Transformed Table";
for(int row = 0; row < dt.Rows.Count; row++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[row + 2, i + 1] = dt.Rows[row][i].ToString();
}
}
workBook.SaveAs("C:\\Users\\******\\Downloads\\test-file.xlsx");
workBook.Close();
excel.Quit();
The end result is an empty sheet.
Based on on the suggestions in this post: How to export DataTable to Excel I was able to use the following code to generate a csv file that did what I needed:
var dtLines = new List<string>();
string[] columnNames = dt.Columns
.Cast<DataColumn>()
.Select(column => column.ColumnName)
.ToArray();
var header = string.Join(",", columnNames.Select(name => $"\"{name}\""));
dtLines.Add(header);
var valueLines = dt.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray.Select(val => $"\"{val}\"")));
dtLines.AddRange(valueLines);
File.WriteAllLines("excel.csv", dtLines);
I am exporting my DataTable to Excel.
So before exporting, I added a new row, I want to set some background color to this row.
Here is my code...
DataRow newRow = datatable3.NewRow();
for (int i = 0; i < datatable3.Columns.Count; i++)
{
newRow[i] = "Hello";
}
//newRow.BackGroundColor = "Red" - Something like this.
Here I am exporting my DataTable to Excel.
using (XLWorkbook wb = new XLWorkbook())
{
foreach (DataTable dt in ds.Tables)
{
//Add DataTable as Worksheet.
wb.Worksheets.Add(dt, dt.TableName.ToString());
}
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
return File(MyMemoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ext);
}
}
It is showing like this .
How to change row background color?
it looks like you are using ClosedXMS dll. check their documentation on using colors
#Gopal
Just being a little specific to #Conor's answer!. You can try this-
//For a specific Datatable in a list of multiple
var ws = wb.Worksheets.Add(dt, dt.TableName.ToString());
for (int j = 1; j <= ds.Tables[3].Columns.Count; j++) //This is for fourth datatable/sheet
{
ws.Cell(2, j).Style.Fill.BackgroundColor = XLColor.FromArgb(255, 255, 0); //All columns of second row
}
XlColor.FromArgb(//RGB Color Code); This static method gives you the liberty of specifying the RGB color code which you can easily get through the excel template you are using.
You can use the Interior property found on an Excel.Range.
// The following just shows how the variables are created (based on creating a new Excel Spreadsheet)
var xlApp = new Excel.Application();
var xlWorkbook = xlApp.Workbooks.Add(Missing.Value);
var xlWorksheet = xlWorkbook.Worksheets[1];
// Now the actual code needed
var xlRange = xlWorksheet.UsedRange;
// This select the entire top row, but you can select your own range based on your data
var titleRange = xlRange.Range["A1", string.Concat(((char)(xlRange.Columns.Count + 64)), 1)];
// The following line sets the fill colour
titleRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);
When I am creating an Excel sheet using DocumentFormat.OpenXml is there any way to specify that I want a range of cells (really the whole sheet) to be in the "Format as Table" (CTRL+T) representation? Or is this not available in the OpenXML library? I can't seem to find anything that says either way. Thank you.
While I'm pretty sure you can do what you want purely with the OpenXML library, you also have the option of including the ClosedXML library which makes working with Excel a whole lot easier.
If I understand your question correctly, you are just looking for taking a data set of some kind and dump it as a table in a Excel-file, in which case, if you can boil your data down to a DataTable in C# the following should help you
//create some dummy table for this test
DataTable table = new DataTable();
//make a few columns
table.Columns.AddRange(
new DataColumn[] { new DataColumn("Column 1",typeof(int)),
new DataColumn("Column 2", typeof(int)),
new DataColumn("Column 3", typeof(int)) }
);
//populate with some randomness
Random r = new Random();
for (int i = 0; i < 100; i++)
{
var newRow = table.NewRow();
newRow[0] = r.Next(0, 10);
newRow[1] = r.Next(0, 10);
newRow[2] = r.Next(0, 10);
table.Rows.Add(newRow);
}
//create workbook
XLWorkbook wb = new XLWorkbook();
var sheet = wb.AddWorksheet("My datatable");
//just showing how to add a bit of extra data to the sheet, not required
sheet.Cell(1, 1).SetValue<string>("Title: this is just a test");
sheet.Cell(1, 3).SetValue<string>("Date: " + DateTime.Now);
//dump table in sheet
sheet.Cell(2, 1).InsertTable(table);
sheet.Columns().AdjustToContents();
wb.SaveAs(#"c:\test\dtable.xlsx",false);
This will result in the following Excel-document
I hope this helps!
I've found how to read first line from Excel file with specific sheet name, but in my case I have to read first line of the first sheet.
How can I realize that or I have to use CSV instead of XLS?
Did you take a look at the EPPlus library? It makes very easy to work with excel files.
Here is how you would do that using EPPlus:
FileInfo existingFile = new FileInfo("yourfilepathname");
using (var package = new ExcelPackage(existingFile))
{
ExcelWorkbook workbook = package.Workbook;
if (workbook != null && workbook.Worksheets.Count > 0)
{
//Gets the first worksheet. You can use index also to select your worksheet.
ExcelWorksheet worksheet = workbook.Worksheets.First();
int rowIndex = 0;
int colIndex = 0;
//To get the first cell:
var cellValue = worksheet.Cells[rowIndex, colIndex].Value;
//YOU CAN ALSO DO A LOOP TO GET ALL VALUES FROM THE FIRST ROW.
}
}
NPOI is another good option and it can handle XLS files too.
Here's a snippet of NPOI code:
HSSFWorkbook _hssfworkbook = new HSSFWorkbook(OpenFileStream(filePath));
//Getting the sheet
_currentSheet = _hssfworkbook.GetSheetAt(0);
//Getting the row:
_row = CurrentSheet.GetRow(0);
//Getting the cell
_cell = _row.GetCell(0);
Have you considered SpreadsheetLight? Here's how you do it:
SLDocument sl = new SLDocument("YourExcelFile.xlsx", "TheSheetName");
string FirstLine = sl.GetCellValueAsString("A1");
sl.CloseWithoutSaving();
Disclaimer: I wrote SpreadsheetLight.