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.
Related
I copy the data from one location to another and am able to read and print all values. But not able to append the column in the Excel file. I need to Append three columns in the beginning (Ex: 'A').
private void btnUpload_Click(object sender, RoutedEventArgs e)
{
ApplicationClass app = new ApplicationClass();
Workbook book = null;
Worksheet sheet = null;
Range range = null;
try
{
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
book = app.Workbooks.Open(#"C:\Windows\Temp\" + FileName, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[1];
// get a range to work with
range = sheet.get_Range("A1", Missing.Value);
// get the end of values to the right (will stop at the first empty cell)
range = range.get_End(XlDirection.xlToRight);
// get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
range = range.get_End(XlDirection.xlDown);
// get the address of the bottom, right cell
string downAddress = range.get_Address(
false, false, XlReferenceStyle.xlA1,
Type.Missing, Type.Missing);
// Get the range, then values from a1
range = sheet.get_Range("A1", downAddress);
object[,] values = (object[,])range.Value2;
// Value2 is a two dimenial array dime one = row, dime two = column.
Console.WriteLine("Col Count: " + values.GetLength(1).ToString());
Console.WriteLine("Row Count: " + values.GetLength(0).ToString());
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["A1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["A1"];
oRng.Value2 = "Discount";
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["B1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["B1"];
oRng.Value2 = "NOTHING";
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["C1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["C1"];
oRng.Value2 = "HELLO";
}
catch (Exception k)
{
Console.WriteLine(k);
}
finally
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
MessageBox.Show("File Uploaded Successfully. Please Wait...!");
}
}
You only need to set the value of the cell. Don't use "A1" as cell because you need the column number: A is the first letter, so it needs to be column 1 and B is the second letter, needs to be column 2 etc. In the following code you can see how to do it correctly:
Excel.Application app = new Excel.Application();
Excel.Workbooks workbooks = app.Workbooks;
string filename = #"yourFilename";
workbooks.Open(filename);
Excel.Workbook workbook = workbooks.Item[1];
Excel.Sheets worksheets = workbook.Worksheets;
Excel.Worksheet worksheet = worksheets.Item[1];
Excel.Range cells = worksheet.UsedRange;
cells[1, 2] = "Hello";//Set value for row 1 and column 2 (A1)
cells[1, 3] = "World";//Set value for row 1 and column 3 (B1)
workbook.Save();//Save Excel-File
app.Quit();
Console.ReadKey();
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.
I want to insert String[][] (2D array) to excel instead of "cell by cell" or by Row.
Another thing:
I want to open a template XLS file, write into it and save it with a different name.
I tried to search google for 2 days already.
Please help me :-)
(in C# WPF)
what i finally did is using object[,], and insert ro by row
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ExcelFile);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range firstCell = xlWorkSheet.get_Range("A1", Type.Missing);
Excel.Range lastCell = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range worksheetCells = xlWorkSheet.get_Range(firstCell, lastCell);
int rowCount = worksheetCells.Rows.Count;
int colCount = worksheetCells.Columns.Count;
object[,] cellFormulas = new String[rowCount, colCount];
cellFormulas = worksheetCells.Formula as object[,];
// String[][] ResultMatrix = new String[rowCount][];
xlWorkBook.Close(true, misValue, misValue);
xlApp.Workbooks.Close();'
You want something like:
Although I think it will only work on jagged arrays and not 2d arrays. Not tested on 2d arrays.
var startCell = Worksheet.Cells[row, col];
var endCell = Worksheet.Cells[row, col];
var writeRange = (Excel.Range)Worksheet.Cells[startCell, endCell];
writeRange.Value = myArray;
I can solve the first problem which is:
I want to insert String [] [] (2D array) to excel instead "cell by cell" or by Row.
In first you should convert String[][] to String[,] and then use this (I tested it):
public static void ExportToExcel(String[,] data, String sheetName, String path)
{
var dt = new DataTable();
for (var row = 0; row < data.GetLength(0); ++row)
{
for (var col = 0; col < data.GetLength(1); col++)
{
dt.Rows[row][col] = data[row, col];
}
}
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
oWB = oXL.Workbooks.Add(Missing.Value);
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = sheetName;
var rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (var i = 1; i < dt.Columns.Count + 1; i++)
{
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
oSheet = null;
oWB.SaveAs(path, 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();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
Note: use should add Microsoft.Office.Interop.Excel in your references.
First off I apologize I have asked this before but I never got an answer for it due to posting at quiet time of day.
I'm trying to read data from an xlsx document columns into array lists on a form based program so I can then call in various bits of data to manipulate or simply show onscren but can't get some code to work. I searched the forums and found this which according to the poster works but I'm having problems. I'm literally stuck on the matter as I've never had to write any code that involved excel.
The errors it throws are the words "Server, Missing & session" do not exist in the current context. I'm aware session isn't part of the winforms applications but dont know what to do about it.
using Microsoft.Office.Interop.Excel;
This is the main code
string filePath = "SampleData.xlsx";
try
{
Excel.Application appExl;
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(filePath);
workbook = appExl.Workbooks.Open(Server.MapPath(filePath), Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
int Cnum = 0;
int Rnum = 0;
ShtRange = NwSheet.UsedRange;
DataTable dt = new DataTable();
for (int row = 1; row <= ShtRange.Rows.Count; row++)
{
string str = Convert.ToString((ShtRange.Cells[row, 1] as Excel.Range).Value2);
dt.Columns.Add(str);
}
workbook.Close(true);
appExl.Quit();
Session["data"] = dt;
return true;
}
catch (Exception ex)
{
return false;
}
Is this a better representation of what it should be like?
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
string FilePath = "SampleData.xlsx";
Excel.Application appExl;
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(FilePath);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
int Cnum = 0;
int Rnum = 0;
ShtRange = NwSheet.UsedRange;
DataTable dt = new DataTable();
for (int row = 1; row <= ShtRange.Rows.Count; row++)
{
string str = Convert.ToString((ShtRange.Cells[row, 1] as Excel.Range).Value2);
dt.Columns.Add(str);
}
workbook.Close(true);
appExl.Quit();
I believe you need to add the following references to your project:
System.Web
System.Reflection
You may also need to add the following to your code:
Using System.Web
Using System.Reflection
If this is a Winforms application, you won't need the System.web reference and you'll need to replace 'Server.MapPath(filePath)' with a filepath Instead of 'Session["data"]' you will probably want to use a DataGrid.
Also looks like you are trying to open the file twice in succession. Not sure why.
I have a Gridview which i fill with a Datatable. On the webpage the user has to be able to download an excel file with the contents of the Gridview. So mi thought the easiest way to save the files is to save the datatable as an excel file. I have troied this method, which i found here on stackoverflow.
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;
}
Bu i get a build error stating that "The name Missing does not exist in the current context" and i cant seem to figure out why? can anyone help ?
the code is pasted from this stackoverflow page here
According to msdn here, Missing.Value is defined in System.Reflection. You should add a reference to this namespace.
using System.Reflection;