I'm a student of Economic Sciences and i'm making a Program for my Final Paper about stock market. But, when i try to run my code in C# using EPPLUS, it doesn't working well. The STOCKHISTORY Formula isn't calculating and "#" is being inserted before the formula.
string Equity = "PETR4", FDate = "01/01/2019", LDate = "01/01/2022";
using (ExcelPackage Excel = new ExcelPackage(new FileInfo("Stock.xlsx")))
{
var Plan = Excel.Workbook.Worksheets.Add("Base");
Plan.Cells[1, 1].Value = FDate;
Plan.Cells[1, 2].Value = LDate;
Plan.Cells[1, 3].Value = Equity;
Plan.Cells[2, 1].Formula = $"STOCKHISTORY(C1, A1, B1)";
Excel.Workbook.Calculate();
Excel.Save();
Excel.Dispose();
}
Related
I know that this problem may be addressed in another asked question, is not cause I lost 2 days trying them all.
Lets start the topic:
-I have an desktop app made in Visual Studio Express 2017, C# code used.
-I take 3 variables that I want to store in an excel document that has multiple sheets: Overtime nr. of hours, Day, comment.
Every sheet belongs to an individual that is based on pc username.
string datforOV = monthCalendar1.SelectionRange.Start.ToShortDateString(); //data string
double hours = decimal.ToDouble(numericUpDown1.Value) + decimal.ToDouble(numericUpDown2.Value) * 0.1; //number of hours
string box = richTextBox1.Text; //content of text box
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet xlsht = new Microsoft.Office.Interop.Excel.Worksheet();
string path = #"Z\OLP.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets[Environment.UserName];
I need to add a new row, in the sheet named already after the Username, and fill the first column with nr of hours, second column with the day, and the next one with the comment.
Please help me cause I started losing my minds. Thank in advance.
You can try the following code to add a new row to your named sheet excel.
using Excel = Microsoft.Office.Interop.Excel;
private void button1_Click(object sender, EventArgs e)
{
string datforOV = monthCalendar1.SelectionRange.Start.ToShortDateString(); //data string
double hours = decimal.ToDouble(numericUpDown1.Value) + decimal.ToDouble(numericUpDown2.Value) * 0.1; //number of hours
string box = richTextBox1.Text; //content of text box
Excel.Application xlApp = new Excel.Application();
string path = #"E:\1.xlsx";
Excel.Workbook workbook = xlApp.Application.Workbooks.Open(path);
Excel.Worksheet xlsht =workbook.Worksheets[Environment.UserName];
Excel.Range range = xlsht.UsedRange;
int rowcount = range.Rows.Count;
Excel.Range next= (Excel.Range)xlsht.Rows[rowcount+1];
next.Insert(); //Another method to add new row
xlsht.Cells[rowcount + 1, 1] = datforOV;
xlsht.Cells[rowcount + 1, 2] = hours;
xlsht.Cells[rowcount + 1, 3] = box;
workbook.Save();
workbook.Close();
xlApp.Quit();
MessageBox.Show("sucess");
}
Result:
I'm using EPPlus to write data to Excel, which works great. I'm writing a header row from column A to column AI and am using the code below to write the data
(subset of the code)
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(customer);
ws.Cells["A1"].Value = "First Name";
ws.Cells["B1"].Value = "Last Name";
ws.Cells["C1"].Value = "Address1";
ws.Cells["D1"].Value = "Address2";
ws.Cells["E1"].Value = "City";
ws.Cells["F1"].Value = "State";
ws.Cells["G1"].Value = "Zip";
ws.Cells["H1"].Value = "Phone";
//keep writing data to I, J, K, L, etc
ws.Cells["AF1"].Value = "Hire Date";
ws.Cells["AG1"].Value = "Manager Name";
ws.Cells["AH1"].Value = "Manager Hire Date";
ws.Cells["AI1"].Value = "Simlcam Number";
FileInfo fi = new FileInfo("C:\\Test\\EPPlusWorkbook.xlsx");
await pck.SaveAsAsync(fi);
}
Now this code writes headers perfectly, UNTIL it reaches cell AF1 then for whatever reason the no further header info is written to the workbook.
Stepping thro the code shows that the lines of code are hit so there is no error displayed.
I want to insert value on my excel ,but i have a problem when i run my application, its create a new file excel ,doesnt insert value into existing file,
using (ExcelPackage excel = new ExcelPackage())
{
excel.Workbook.Worksheets.Add("Worksheet1");
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[2, 1].Value = "ID";
FileInfo excelFile = new FileInfo(#"E:\ExcelTest.xls");
excel.SaveAs(excelFile);
I want my Program insert into existing file ,not create a new one,
how i can solve this?
The EPPlus Wiki Getting Started covered this exact scenario.
FileInfo excelFile = new FileInfo(#"E:\ExcelTest.xls");
using (ExcelPackage excel = new ExcelPackage(excelFile))
{
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[2, 1].Value = "ID";
excel.Save();
}
I have a few different dictionaries with different categories of information and I need to output them all into an xls or csv file with multiple spreadsheets. Currently, I have to download each excel file for a specific date range individually and then copy and paste them together so they're on different sheets of the same file. Is there any way to download all of them together in one document? Currently, I use the following code to output their files:
writeCsvToStream(
organize.ToDictionary(k => k.Key, v => v.Value as IacTransmittal), writer
);
ms.Seek(0, SeekOrigin.Begin);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.ContentType = "application/octet-stream";
ms.CopyTo(Response.OutputStream);
Response.End();
where writeCsvToStream just creates the text for the individual file.
There are some different options you could use.
ADO.NET Excel driver - with this API you can populate data into Excel documents using SQL style syntax. Each worksheet in the workbook is a table, each column header in a worksheet is a column in that table etc.
Here is a code project article on the exporting to Excel using ADO.NET:
http://www.codeproject.com/Articles/567155/Work-with-MS-Excel-and-ADO-NET
The ADO.NET approach is safe to use in a multi-user, web app environment.
Use OpenXML to export the data
OpenXML is a schema definition for different types of documents and the later versions of Excel (the ones that use .xlsx, .xlsm etc. instead of just .xls) use this format for the documents. The OpenXML schema is huge and somewhat cumbersome, however you can do pretty much anything with it.
Here is a code project article on exporting data to Excel using OpenXML:
http://www.codeproject.com/Articles/692121/Csharp-Export-data-to-Excel-using-OpenXML-librarie
The OpenXML approach is safe to use in a multi-user, web app environment.
A third approach is to use COM automation which is the same as programmatically running an instance of the Excel desktop application and using COM to control the actions of that instance.
Here is an article on that topic:
http://support.microsoft.com/kb/302084
Note that this third approach (office automation) is not safe in a multi-user, web app environment. I.e. it should not be used on a server, only from standalone desktop applications.
If you're open to learning a new library, I highly recommend EPPlus.
I'm making a few assumptions here since you didn't post much code to translate, but an example of usage may look like this:
using OfficeOpenXml;
using OfficeOpenXml.Style;
public static void WriteXlsOutput(Dictionary<string, IacTransmittal> collection) //accepting one dictionary as a parameter
{
using (FileStream outFile = new FileStream("Example.xlsx", FileMode.Create))
{
using (ExcelPackage ePackage = new ExcelPackage(outFile))
{
//group the collection by date property on your class
foreach (IGrouping<DateTime, IacTransmittal> collectionByDate in collection
.OrderBy(i => i.Value.Date.Date)
.GroupBy(i => i.Value.Date.Date)) //assuming the property is named Date, using Date property of DateTIme so we only create new worksheets for individual days
{
ExcelWorksheet eWorksheet = ePackage.Workbook.Worksheets.Add(collectionByDate.Key.Date.ToString("yyyyMMdd")); //add a new worksheet for each unique day
Type iacType = typeof(IacTransmittal);
PropertyInfo[] iacProperties = iacType.GetProperties();
int colCount = iacProperties.Count(); //number of properties determines how many columns we need
//set column headers based on properties on your class
for (int col = 1; col <= colCount; col++)
{
eWorksheet.Cells[1, col].Value = iacProperties[col - 1].Name ; //assign the value of the cell to the name of the property
}
int rowCounter = 2;
foreach (IacTransmittal iacInfo in collectionByDate) //iterate over each instance of this class in this igrouping
{
int interiorColCount = 1;
foreach (PropertyInfo iacProp in iacProperties) //iterate over properties on the class
{
eWorksheet.Cells[rowCounter, interiorColCount].Value = iacProp.GetValue(iacInfo, null); //assign cell values by getting the value of each property in the class
interiorColCount++;
}
rowCounter++;
}
}
ePackage.Save();
}
}
}
Thanks for the ideas! I was eventually able to figure out the following
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook ExcelWorkBook = null;
Excel.Worksheet ExcelWorkSheet = null;
ExcelApp.Visible = true;
ExcelWorkBook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
List<string> SheetNames = new List<string>()
{ "Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6", "Sheet7"};
string [] headers = new string []
{ "Field 1", "Field 2", "Field 3", "Field 4", "Field 5" };
for (int i = 0; i < SheetNames.Count; i++)
ExcelWorkBook.Worksheets.Add(); //Adding New sheet in Excel Workbook
for (int k = 0; k < SheetNames.Count; k++ )
{
int r = 1; // Initialize Excel Row Start Position = 1
ExcelWorkSheet = ExcelWorkBook.Worksheets[k + 1];
//Writing Columns Name in Excel Sheet
for (int col = 1; col < headers.Length + 1; col++)
ExcelWorkSheet.Cells[r, col] = headers[col - 1];
r++;
switch (k)
{
case 0:
foreach (var kvp in Sheet1)
{
ExcelWorkSheet.Cells[r, 1] = kvp.Value.Field1;
ExcelWorkSheet.Cells[r, 2] = kvp.Value.Field2;
ExcelWorkSheet.Cells[r, 3] = kvp.Value.Field3;
ExcelWorkSheet.Cells[r, 4] = kvp.Value.Field4;
ExcelWorkSheet.Cells[r, 5] = kvp.Value.Field5;
r++;
}
break;
}
ExcelWorkSheet.Name = SheetNames[k];//Renaming the ExcelSheets
}
//Activate the first worksheet by default.
((Excel.Worksheet)ExcelApp.ActiveWorkbook.Sheets[1]).Activate();
//Save As the excel file.
ExcelApp.ActiveWorkbook.SaveCopyAs(#"out_My_Book1.xls");
I am using VS2013 Ultimate, with Office 2013 (PowerPoint, Excel and Word all installed). I am coding in C#.
I am creating a PowerPoint presentation using C#. So far, I have managed to accomplish everything that I have wanted to do. However, I am having problems attempting to create a chart. My understanding is that Excel is used to manage the data (in a worksheet). I have the following code, which will produce a chart with two series in a PowerPoint slide. The problem is that 'sometimes' the chart does not get added to the slide. It gets added, the worksheet appears and the data is modified and the chart disappears from the slide! I also notice 2 instances of Excel firing up but I cannot understand why. Can anyone shed any light on this please? Thanks.
public void CreateChart(PPT.Slide slide)
{
slide.Layout = PPT.PpSlideLayout.ppLayoutBlank;
var chart = slide.Shapes.AddChart(XlChartType.xlLine, 10f, 10f, 900f, 400f).Chart;
var workbook = (EXCEL.Workbook)chart.ChartData.Workbook;
workbook.Windows.Application.Visible = true;
var dataSheet = (EXCEL.Worksheet)workbook.Worksheets[1];
dataSheet.Cells.ClearContents();
dataSheet.Cells.Range["A1"].Value2 = "Bananas";
dataSheet.Cells.Range["A2"].Value2 = "Apples";
dataSheet.Cells.Range["A3"].Value2 = "Pears";
dataSheet.Cells.Range["A4"].Value2 = "Oranges";
dataSheet.Cells.Range["B1"].Value2 = "1000";
dataSheet.Cells.Range["B2"].Value2 = "2500";
dataSheet.Cells.Range["B3"].Value2 = "4000";
dataSheet.Cells.Range["B4"].Value2 = "3000";
var sc = (PPT.SeriesCollection)chart.SeriesCollection();
do
{
var seriesToDelete = sc.Item(1);
seriesToDelete.Delete();
}
while (sc.Count != 0);
var series1 = sc.NewSeries();
series1.Name = "Pauls Series";
series1.XValues = "'Sheet1'!$A$1:$A$2";
series1.Values = "'Sheet1'!$B$1:$B$2";
series1.ChartType = XlChartType.xlLine;
var series2 = sc.NewSeries();
series2.Name = "Seans Series";
series2.XValues = "'Sheet1'!$A$1:$A$2";
series2.Values = "'Sheet1'!$B$3:$B$4";
series2.ChartType = XlChartType.xlLine;
chart.HasTitle = true;
chart.ChartTitle.Font.Italic = true;
chart.ChartTitle.Text = "My First Chart!";
chart.ChartTitle.Font.Size = 12;
chart.ChartTitle.Font.Color = Color.Black.ToArgb();
chart.ChartTitle.Format.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
chart.ChartTitle.Format.Line.ForeColor.RGB = Color.Black.ToArgb();
chart.HasLegend = true;
chart.Legend.Font.Italic = true;
chart.Legend.Font.Size = 10;
chart.Refresh();
}
so, putting a chart.refresh() within the Do{} block has resolved my problems! How odd!?!