Insert 2D array into excel in C# WPF - c#

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.

Related

how to get the continuation of the Same Excel sheet from next datatable Export to Excel from c#

When I export a data table to excel how can I identify how many rows are inserted to Excel, and get the next row position of the same Excel sheet to insert the next data table values?
var lines = new List<string>();
string[] columnNames = dataTable.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dataTable.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("excel.csv",lines);
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public static void ReadExistingExcel()
{
string path = #"C:\Tool\Reports1.xls";
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount= range.Rows.Count;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[rowCount + index, 1] = rowCount +index;
mWSheet1.Cells[rowCount + index, 2] = "New Item"+index;
}
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}

Save DataTable data in Excel file asp.Net

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;

How To Change XLS Column DataType Using .NET

I am trying to export a datatable into an xls file. Below are my code:
using ExcelIt = Microsoft.Office.Interop.Excel;
protected void Export2xlsWorkBook(string filename)
{
if (filename != string.Empty)
{
if (filename.EndsWith(".xls"))
filename = txtNewFileName.Text + ".xls";
}
else
filename = "NewFile.xls";
filename = "C:\\Documents and Settings\\My Documents\\Exported XLS\\" + filename;
ExcelIt.Application objXL = new ExcelIt.Application();
ExcelIt.Workbook oWB;
ExcelIt.Worksheet oSheet;
ExcelIt.Range oRange;
objXL.Visible = true;
objXL.DisplayAlerts = false;
oWB = objXL.Workbooks.Add(Missing.Value);
DataTable dt = CreateDataTable();
oSheet = (ExcelIt.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Exported Table";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int 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();
}
}
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();
oRange = oSheet.get_Range(oSheet.Cells[1, 2], oSheet.Cells[rowCount + 10, dt.Columns.Count]);
oSheet.Protection.AllowEditRanges.Add("NonePK", oRange, Missing.Value);
oRange = oSheet.get_Range(oSheet.Cells[rowCount + 1, 1], oSheet.Cells[rowCount + 10, 1]);
oSheet.Protection.AllowEditRanges.Add("PKEmptyRow", oRange, Missing.Value);
oSheet._Protect(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oSheet = null;
oRange = null;
oWB.SaveAs(filename, ExcelIt.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
ExcelIt.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
objXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
For certain reasons, I would like to:
Set all columns datatype into text.
Currently as I didn't specify anything the datatypes are set into "general" instead.
Can someone advise me on how to achieve this?
Regards
you can use Range.NumberFormat Property
Range usedRange = oSheet.UsedRange;
usedRange.NumberFormat = "#";

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.

Import excel sheet data to datagrid without using oledb

In my Windows based application(C#)
i want to import excel sheet to show its data in DatatGridView
i dont want to use oledb
any Help
using Excel = Microsoft.Office.Interop.Excel;
You'll obviously need to add the reference to your project, and then it's plain simple :)
private void ProcessExcel(string filepath)
{
Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass();
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
Excel.Range range = worksheet.UsedRange;
System.Array myvalues = (System.Array)range.Cells.Value2;
int vertical = myvalues.GetLength(0);
int horizontal = myvalues.GetLength(1);
string[] headers = new string[horizontal];
string[] data = new string[horizontal];
DataTable ResultsHeader = New DataTable();
DataSet ds = New DataSet();
for (int x = 1; x <= vertical; x++)
{
Utils.inicializarArrays(datos);
for (int y = 1; y <= horizontal; y++)
{
if (x == 1)
{
headers[y - 1] = myvalues.GetValue(x, y).ToString();
}
else
{
string auxdata = "";
if (myvalues.GetValue(x, y) != null)
auxdata = myvalues.GetValue(x, y).ToString();
data[y - 1] = auxdata;
}
}
if(x == 1) //headers
{
for(int w = 0; w < horizontal; w++)
{
ResultsHeader.Columns.Add(New DataColumn(headers[w], GetType(string)));
}
ds.Tables.Add(ResultsHeader);
}
else
{
DataRow dataRow = ds.Tables[0].NewRow();
for(int w = 0; w < horizontal; w++)
{
dataRow(headers[w]) = data[w]
}
ds.Tables[0].Rows.Add(dataRow);
}
}
DataView myDataView = new DataView();
myDataView.Table = ds.Tables[0];
MydataGrid.CurrentPageIndex = 0;
MydataGrid.DataSource = myDataView;
MydataGrid.DataBind();
}
I'm late to the party, but I have something worthwhile to add! I tried Juan's code and it didn't compile out-of-the-box. I modified it a little bit after researching the internet for a few more hours and got it to do exactly what the original poster asked (as I needed to do the same thing). I had to piece code together from other sources, and unfortunately, I did not keep track of what bits and pieces I tried and changed so I can't comment much about it.
The following code works in Visual Studio 2008 with .NET 3.5. Also, the formatting is lost when the data is put into the array (for example, dates become doubles which require a conversion with DateTime.FromOADate() to change it back). The issue with that is you can't tell if a value is an actual double or a date from a coding viewpoint, but if you know ahead of time a column is going to be a date, then format it as you insert the data into the table.
private void processExcel(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
DataTable dt = new DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1,i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
dataGridView1.DataSource = dt;
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Those codes above does not work.
That code works for me (.NET Framework 4.7.1)
private void processExcel(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
DataTable dt = new DataTable();
// must start with index = 1
// get header information
try
{
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(Convert.ToString(myValues.GetValue(1, i))));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] rows = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
rows[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = rows;
dt.Rows.Add(row);
}
// assign table to default data grid view
dataGridView1.DataSource = dt;
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

Categories