C# Interop.Excel can't find dll - c#

this ist my first VS and C# project. I want to access an excel file and add some data. Pretty much standard I guess. So I used a code example from the microsoft page (see below). No red underlines in the editor. But when I run it, I get the error message below. I guess it is not a problem of the code. Can anyone help me or send me a helpful link?
I use Visual Studio 2019 Community and Office 365 64-bit.
Error:
Message=Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))
I already tried this solution, but it didn't work.
VB: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace test2Excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[4, 0] = "Adam";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
//Manipulate a variable number of columns for Quarterly Sales Data.
DisplayQuarterlySales(oSheet);
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
private void DisplayQuarterlySales(Excel._Worksheet oWS)
{
Excel._Workbook oWB;
Excel.Series oSeries;
Excel.Range oResizeRange;
Excel._Chart oChart;
String sMsg;
int iNumQtrs;
//Determine how many quarters to display data for.
for (iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)
{
sMsg = "Enter sales data for ";
sMsg = String.Concat(sMsg, iNumQtrs);
sMsg = String.Concat(sMsg, " quarter(s)?");
DialogResult iRet = MessageBox.Show(sMsg, "Quarterly Sales?",
MessageBoxButtons.YesNo);
if (iRet == DialogResult.Yes)
break;
}
sMsg = "Displaying data for ";
sMsg = String.Concat(sMsg, iNumQtrs);
sMsg = String.Concat(sMsg, " quarter(s).");
MessageBox.Show(sMsg, "Quarterly Sales");
//Starting at E1, fill headers for the number of columns selected.
oResizeRange = oWS.get_Range("E1", "E1").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";
//Change the Orientation and WrapText properties for the headers.
oResizeRange.Orientation = 38;
oResizeRange.WrapText = true;
//Fill the interior color of the headers.
oResizeRange.Interior.ColorIndex = 36;
//Fill the columns with a formula and apply a number format.
oResizeRange = oWS.get_Range("E2", "E6").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Formula = "=RAND()*100";
oResizeRange.NumberFormat = "$0.00";
//Apply borders to the Sales data and headers.
oResizeRange = oWS.get_Range("E1", "E6").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;
//Add a Totals formula for the sales data and apply a border.
oResizeRange = oWS.get_Range("E8", "E8").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Formula = "=SUM(E2:E6)";
oResizeRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle
= Excel.XlLineStyle.xlDouble;
oResizeRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Weight
= Excel.XlBorderWeight.xlThick;
//Add a Chart for the selected data.
oWB = (Excel._Workbook)oWS.Parent;
oChart = (Excel._Chart)oWB.Charts.Add(Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
//Use the ChartWizard to create a new chart from the selected data.
oResizeRange = oWS.get_Range("E2:E6", Missing.Value).get_Resize(
Missing.Value, iNumQtrs);
oChart.ChartWizard(oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oSeries = (Excel.Series)oChart.SeriesCollection(1);
oSeries.XValues = oWS.get_Range("A2", "A6");
for (int iRet = 1; iRet <= iNumQtrs; iRet++)
{
oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
String seriesName;
seriesName = "=\"Q";
seriesName = String.Concat(seriesName, iRet);
seriesName = String.Concat(seriesName, "\"");
oSeries.Name = seriesName;
}
oChart.Location(Excel.XlChartLocation.xlLocationAsObject, oWS.Name);
//Move the chart so as not to cover your data.
oResizeRange = (Excel.Range)oWS.Rows.get_Item(10, Missing.Value);
oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;
oResizeRange = (Excel.Range)oWS.Columns.get_Item(2, Missing.Value);
oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
}
}
}

Interop always requires MS Office installed on your PC.
Looks like you are using Office 365 on web.
Anyways, the library excellibrary , can help
https://code.google.com/archive/p/excellibrary/
The Other option is using npoi NuGet which is a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
https://github.com/nissl-lab/npoi
https://www.nuget.org/packages/NPOI/

Related

interop error HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH) on server

I am having a problem with my app when trying to run on the server.
In my place it works fine but when passed to the server it fails to try to create the pivotcache.
Excel has permissions on the server with the user IIS, on my computer I have Office 365 and Office 2010 on server.
please help.error
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
//Create COM Objects. Create a COM object for everything that is referenced
oApp = new Excel.Application();
oBook = oApp.Workbooks.Open(fileTest);
oSheet = oBook.Sheets[1];
//Range = oSheet.Range["A9","BN36"];
//Excel.Worksheet oSheet2 = oBook.Worksheets.Add();
//oSheet2.Name = "Pivot Table";
//oApp = new Excel.Application();
//oBook = oApp.Workbooks.Add();
//oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//oSheet.Cells[1, 1] = "Name";
//oSheet.Cells[1, 2] = "Salary";
//oSheet.Cells[2, 1] = "Frank";
//oSheet.Cells[2, 2] = 150000;
//oSheet.Cells[3, 1] = "Ann";
//oSheet.Cells[3, 2] = 300000;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
//// now capture range of the first sheet = I will need this to create pivot table
Excel.Range oRange = oSheet.Range["A1", "AJ708"];
// create second sheet
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Resumen";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[1, 1];
// create Pivot Cache and Pivot Table heres trow exception error
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
solved.
trying change this line
var oPivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!$A$1:$AL$" + lastUsedRow);
the correct format to pass a range on office 2010 i think so.

C# Write to an open Excel file using Interop

I am having a ridiculously hard time with this, but I need to be able to connect to an open excel file using Interop and then write to that file.
The file is opened by an outside process and then this application comes in later to write to the workbook. I can get it to open a file and write to the active workbook. but I can't find a way to connect to a previous workbook and write.
I had been using Marshal.GetActiveObject but I will soon be running the application on a computer with multiple files open and need to write to one that will most likely not bee the active one.
Update :
System.Runtime.InteropServices.Marshal.BindToMoniker can be used to access file that is opened in Excel, or opens it if it is not already opened :
var wb = Marshal.BindToMoniker(#"C:\x.xlsx") as Microsoft.Office.Interop.Excel.Workbook;
https://blogs.msdn.microsoft.com/eric_carter/2009/03/12/attaching-to-an-already-running-office-application-from-your-application-using-getactiveobject-or-bindtomoniker/
Old answer :
GetObject can be used with reference to Microsoft.VisualBasic (it also opens the file if needed) :
object o = Microsoft.VisualBasic.Interaction.GetObject(#"C:\x.xlsx", "Excel.Application");
var wb = o as Microsoft.Office.Interop.Excel.Workbook;
if (wb != null)
{
Microsoft.Office.Interop.Excel.Application xlApp = wb.Application;
// your code
}
Reference to Microsoft.VisualBasic can probably be avoided by checking the GetObject source code https://github.com/Microsoft/referencesource/blob/master/Microsoft.VisualBasic/runtime/msvbalib/Interaction.vb#L1039
This seems to be C# version
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = null;
try
{
excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
}
catch (COMException exc)
{
// ....
}
obviously assuming that the file is opened by an excel application on the same machine.
But the point is that Marshal.GetActiveObject will always return the first instance it finds on ROT (running object table). This is because Office doesn't register new objects. You have to get the application from the child windows, like suggested in this more complicated answer.
Try it this way.
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
From here:
How to write some data to excel file(.xlsx)
Also, check this out.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

Export To Excel C# Error

I don't get the error that appears in my export to excel code. I have this error
Unable to cast COM object of type 'System.__ComObject' to interface
type 'Microsoft.Office.Interop.Excel.Range'. This operation failed
because the QueryInterface call on the COM component for the interface
with IID '{00020846-0000-0000-C000-000000000046}' failed due to the
following error: No such interface supported (Exception from HRESULT:
0x80004002 (E_NOINTERFACE)).
Here is the code in my gridview, my gridview's name is dgvCommission.
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_elapsed);
timer.Start();
Invoke(new MyDelegate(ShowLabel), "Loading...");
BACS.DateFrom = this.dtFrom.Value.ToShortDateString(); //this.dtFrom.Text;
BACS.DateTo = this.dtTo.Value.ToShortDateString(); //this.dtTo.Text;
BACS.BrokerAgent = BrokerXML;
BACS.Payor = PayorXML;
DS = BACS.GET_SP_BACS_ComputeCommission();
ReadData(DS, this.dgvCommision);
CheckGrid();
Thread.Sleep(1);
timer.Stop();
}
catch
{ }
}
And here is my export to excel code in my form.
private void ExportToExcel()
{
string[] arrays = new string[19];
arrays[0] = "Type";
arrays[1] = "Broker Agent";
arrays[2] = "Payor";
arrays[3] = "Billing #";
arrays[4] = "OR No.";
arrays[5] = "OR Date";
arrays[6] = "Particulars";
arrays[7] = "Mode";
arrays[8] = "Amount Billed";
arrays[9] = "Amount Paid";
arrays[10] = "Non Comm Items";
arrays[11] = "Net";
arrays[12] = "Output VAT";
arrays[13] = "Commissionable Amount";
arrays[14] = "WTAX Rate";
arrays[15] = "WTAX";
arrays[16] = "Net Commission";
arrays[17] = "InputVAT";
arrays[18] = "For Fund Release";
SystemUtil.ExportToExel(DS, arrays);
}
ExportToExcel class code is this:
public void ExportToExel(DataSet ds,string[] arrays)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "EXCEL";
DataTable dt2 = new DataTable();
if (ds.Tables[0] != null)
{
dt2 = ds.Tables[0];
}
int rowCount = 1;
foreach (DataRow dr in dt2.Rows)
{
rowCount += 1;
for (int i = 1; i < dt2.Columns.Count + 1; i++)
{
if (rowCount == 2)
{
oSheet.Cells[1, i] = arrays[i - 1];// dt.Columns[i - 1].ColumnName;
// oSheet.Cells[1,i].Font.Background = System.Drawing.Color.Red;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
////// Resize the columns
//oRange = oSheet.get_Range(1, 23);
////oRange.EntireColumn.AutoFit();
//oRange.Range[1, 2].AutoFit();
// Save the sheet and close
oSheet = null;
// oRange = null;
//oWB.SaveAs(#"c:\REPORTS.xls", Excel.XlFileFormat.xlWorkbookNormal,
// Missing.Value, Missing.Value, Missing.Value, Missing.Value,
// Excel.XlSaveAsAccessMode.xlExclusive,
// Missing.Value, Missing.Value, Missing.Value,
// Missing.Value, Missing.Value);
//oWB.Close(Missing.Value, Missing.Value, Missing.Value);
//oWB = null;
//oXL.Quit();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
The exception error pops up in this code. oSheet.Cells[1, i] = arrays[i - 1];
Do you guys know how can this happen? I don't understand what's wrong in my code.. Please help me on this one. Thanks in advance for your help.
Try changing
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
To
oSheet = (Excel.Worksheet)oXL.ActiveSheet;
Further explanation: MSDN provides the following note regarding the Workbook Interface....
"This interface is implemented by the Visual Studio Tools for Office runtime. It is not intended to be implemented in your code. For more information, see Visual Studio Tools for Office Runtime Overview."
That's why you have to reference the application interface after initializing a new workbook.
Please mark this as answered if it resolved your question.

How to generate line chart from datatable c# winform

i am using Interop.Excel to export data from datatable and generate line chart too.
i could successfully export data to excel from data like this way
public static bool Export(System.Data.DataTable dt, string sheetName)
{
object Missing = System.Reflection.Missing.Value;
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = sheetName;
oSheet.Cells[1, 1] = "Daily Finished Job History " + DateTime.Now.ToString("dd/MM/yyyy");
oSheet.get_Range("A1", "A1").ColumnWidth = 13;
oSheet.get_Range("B1", "B1").ColumnWidth = 13;
oSheet.get_Range("C1", "C1").ColumnWidth = 25;
oSheet.get_Range("A1", "C1").Font.Size = 14;
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").Merge(true);
oSheet.get_Range("A1", "C1").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
oSheet.get_Range("A3", "C3").Font.Bold = true;
int rowCount = 3;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
oSheet.Cells[rowCount, i] = dt.Columns[i - 1].ColumnName;
}
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
//oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
string strParentDirectory = GetParentDirectory();
strParentDirectory = strParentDirectory + "\\Data";
if (!Directory.Exists(strParentDirectory))
{
Directory.CreateDirectory(strParentDirectory);
}
string strFileName = strParentDirectory + "\\DailyFinishedJobHistory_" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
FileStream file = new FileStream(strFileName, FileMode.Create);
file.Close();
oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
Missing, Missing, Missing, Missing,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing, Missing, Missing,
Missing, Missing);
oWB.Close(Missing, Missing, Missing);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
public static string GetParentDirectory()
{
System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
return myDirectory.Parent.Parent.FullName;
}
now i want to generate chart in same sheet based on data from my datatable.
my excel file would look like as follows
i read few article & code to generate chart from this links
http://www.dotnetbull.com/2011/09/exporting-pie-chart-into-excel-file.html
http://csharp.net-informations.com/excel/csharp-excel-chart.htm
http://www.daniweb.com/software-development/csharp/threads/80834/c-and-excel-chart-ranges
but still not being able to understand the code to generate line chart. it would be great help if some help me to generate chart in same sheet like the image i have given here.
thanks
Try this as a starting point:
'Create & Format Chart
Dim oChart As Excel.Chart
oChart = oXL.Parent.Charts.Add
With oChart
.Name = "History"
.HasTitle = True
.ChartTitle.Font.ColorIndex = 11
.ChartTitle.Font.Bold = True
.ChartTitle.Font.Size = 12
.ChartTitle.Font.Name = "Arial"
.ChartTitle.Text = "Job History"
.ChartType = Excel.XlChartType.xlLine
.HasLegend = True
.SeriesCollection(1).XValues = "=Sheet1!$A$4:$A$6"
.SeriesCollection(1).Name = "=Sheet1!$B$3"
.SeriesCollection(2).Name = "=Sheet1!$C$3"
.SeriesCollection(3).Name = "=Sheet1!$D$3"
End With

How to export excel from dataset or datatable in c#?

I want to export data from Dataset or Data Table to Excel file in C# without using Gridview.
I would recommend EPPlus - this solution doesn't require COM nor interop dlls and is very fast. Perfectly suited for web scenarios.
http://epplus.codeplex.com/
http://nuget.org/packages/EPPlus
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//Example how to Format Column 1 as numeric
using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
}
}
Get more ways : 9 Solutions to Export Data to Excel for ASP.NET
I have this code but for this you need to include Excel Com Component
Add reference of Microsoft.Office.Interop.Excel.dll in your project will do task for you.
using Excel = Microsoft.Office.Interop.Excel;
public static bool ExportDataTableToExcel(DataTable dt, string filepath)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
you can use
using Microsoft.Office.Interop.Excel;
to work with excel documents "native"...
Using C# to Create an Excel Document
http://www.codeproject.com/Articles/20228/Using-C-to-Create-an-Excel-Document
But most of the common report Generator/Designers can easily export to excel
also check for Reporting Services if you are using SQL SERVER
Just in case somebody else used the chosen solution and run into the "object does not contain a definition for get_Range" exception. I found the solution here: Worksheet get_Range throws exception. I hope this will save your time.

Categories