excel import using c# - c#

i am working on excel import to grid view using DataTable in c#, but my problem is its working fine on my local system but its redirecting to login page on my online server and i have tried both Microsoft.Office.Interop.Excel & OLEdb connection. but the problem is same. please tell me what is the problem with these or any one have any other function to import Excel data in GridView.
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.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
GridView1.DataSource = dt;
GridView1.DataBind();
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();
}
}

Have a look:
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.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
GridView1.DataSource = dt;
GridView1.DataBind();
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();
}
}

It is better not using MS Office interop in server cases which will bring a lot of performance and memory issues in the future. Recommend using some 3rd party library, for example: https://www.nuget.org/packages/Spread.Services/ to get what you wanted.

Related

Error append column to the end of an existng excel file c#

I want to append the column to the end of an existing excel file with Microsoft.Office.Interop.Excel in c#, I use Microsoft excel 2007, here is my code:
public void UpdateExcel_MSInterop(
string ExcelFile)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
try
{
//define ms excel application
xlApp = new Microsoft.Office.Interop.Excel.Application();
//
int Hwnd = xlApp.Hwnd;
xlApp.DisplayAlerts = false;
//
xlWorkbook = xlApp.Workbooks.Open(ExcelFile, Type.Missing, true);
int SheetIndex = 1;
foreach (Worksheet objSHT in xlWorkbook.Worksheets)
{
if (SheetIndex == 1)// ExcelSheetFullName.Substring(0, ExcelSheetFullName.Length - 1))
{
Range rng = objSHT.UsedRange;
int colCount = rng.Columns.Count;
int rowCount = rng.Rows.Count;
Range newRng = objSHT.get_Range(objSHT.Cells[1, 1], objSHT.Cells[1, colCount]).EntireColumn.Insert(Missing.Value,XlInsertShiftDirection.xlShiftToRight);
newRng.Cells[1, colCount + 1] = "State";
for (int r = 2; r <= rowCount; r++)
{
newRng.Cells[r, colCount + 1] = Products.Rows[r - 2]["state"].ToString();
}
break;
}
SheetIndex++;
}
xlWorkbook.Save();
if (xlWorkbook != null)
xlWorkbook.Close(SaveChanges:true);
if (xlApp != null)
xlApp.Quit();
}
catch (Exception ex)
{
if (xlWorkbook != null)
xlWorkbook.Close();
if (xlApp != null)
xlApp.Quit();
xlWorkbook = null;
xlApp = null;
MessageBox.Show(ex.Message + "\n" + ex.StackTrace.ToString());
throw ex;
}
}
I get error:
object dose not contain a definition for get_Range
How to fix this error, or if my approach is wrong how to append column to the end of an existing excel file,please give me example,Thanks for help.

How to create Excel file in asp.net

I want to create Excel Sheet in asp.net. I have already done code for this and it is working fine in local system but when I am testing it on server then it gives the following error.
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.
My code is.
private static System.Data.DataTable GetDataSet()
{
System.Data.DataTable dt = new System.Data.DataTable("Table");
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Address", Type.GetType("System.String"));
dt.Columns.Add("Phone", Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["Name"] = "Balaji Selvarajan";
dr["Address"] = "Reddiyur";
dr["Phone"] = "000-000-0000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Balaji S";
dr["Address"] = "Kattumannar Koil";
dr["Phone"] = "000-000-0000";
dt.Rows.Add(dr);
return dt;
}
private static void DataSetToExcel(System.Data.DataTable dt, Boolean generateIdentity)
{
try
{
string Filename = HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls";
string imagepath1 = HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls";
FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls");
if (fi.Exists)
{
fi.Delete();
}
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(misValue, misValue, misValue, misValue);
ws.Name = "Test";
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (i == 0)
ws.Cells[1, j + 1] = dt.Columns[j].ColumnName;
ws.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
}
ws.Protect("1235", true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
}
wb.Protect("my", true, true);
wb.Password = "1235";
wb.SaveAs(Filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, "1235", misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
wb.Close(true, misValue, misValue);
xlApp.Visible = true;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
HttpContext.Current.Response.ContentType = "Application/Excel";
string FilePath = imagepath1;
HttpContext.Current.Response.WriteFile(FilePath);
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Test.xls");
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
protected void BtnDn_Click(object sender, EventArgs e)
{
DataSetToExcel(GetDataSet(), false);
}
I am not able to solve this problem please help me. and give me solution as soon as possible please.
I am using Asp.net C#.
Try with this
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
namespace Excel
{
public class ExcelUtlity
{
public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType) {
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
try
{
// Start Excel and get Application object.
excel = new Microsoft.Office.Interop.Excel.Application();
// for making Excel visible
excel.Visible = false;
excel.DisplayAlerts = false;
// Creation a new Workbook
excelworkBook = excel.Workbooks.Add(Type.Missing);
// Workk sheet
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
excelSheet.Name = worksheetName;
excelSheet.Cells[1, 1] = ReporType;
excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString();
// loop through each row and add values to our sheet
int rowcount = 2;
foreach (DataRow datarow in dataTable.Rows)
{
rowcount += 1;
for (int i = 1; i <= dataTable.Columns.Count; i++)
{
// on the first iteration we add the column headers
if (rowcount == 3)
{
excelSheet.Cells[2, i] = dataTable.Columns[i-1].ColumnName;
excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
}
excelSheet.Cells[rowcount, i] = datarow[i-1].ToString();
//for alternate rows
if (rowcount > 3)
{
if (i == dataTable.Columns.Count)
{
if (rowcount % 2 == 0)
{
excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black,false);
}
}
}
}
}
// now we resize the columns
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
excelCellrange.EntireColumn.AutoFit();
Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
border.Weight = 2d;
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dataTable.Columns.Count]];
FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
//now save the workbook and exit Excel
excelworkBook.SaveAs(saveAsLocation);;
excelworkBook.Close();
excel.Quit();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
finally
{
excelSheet = null;
excelCellrange = null;
excelworkBook = null;
}
}
/// FUNCTION FOR FORMATTING EXCEL CELLS
public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool)
{
range.Interior.Color=System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode);
range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor);
if (IsFontbool == true)
{
range.Font.Bold = IsFontbool;
}
}
}
Error 80070005 is an Access Denied error. Try configuring your AppPool to run under LocalSystem (instead of ApplicationPoolIdentity), or try granting permissions for Excel in Component Services:
From the Start menu, click Run and type Dcomcnfg.exe.
In Component Services, click Console root, expand Component Services, expand Computers, expand My computer,expand DCOMConfig.
Search for Microsoft Word 14.0 Object Library. Click on it.
Right click and select Properties.
On security tab, select Customize in "Launch and Activation" section.
Click edit and add identity of app pool under which you application is running.
Repeat above step for "Access Permission"
AppPool account solution is from here: "Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
Component Services Permission answer is from here: Retrieving the COM class factory for component with CLSID failed due to the following error: 80070005 Access is denied.

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

Parse Excel document for keywords using C#

I need to parse the excel document for certain keywords using C# and count the number of their occurrences. These keywords are required to be searched within a certain range, which is not fixed.
Please provide some help for this.
Thanks!
You may try something like this (i'm using Excel Interop here):
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
Excel.Workbook wk = app.Workbooks.Open(#"D:\testExcel.xlsx");
Excel.Worksheet sh = (Excel.Worksheet)wk.ActiveSheet;
Excel.Range rng = sh.get_Range("A1", "Z20");
Console.WriteLine(CountWord(rng, "a"));
wk.Close(false);
app.Quit();
Console.ReadLine();
}
private static int CountWord(Excel.Range rng, string word)
{
int i = 0;
Excel.Range rng1 = rng.Find(word);
if (rng1 != null)
i++;
else
return 0;
string address = rng1.Address;
Console.WriteLine(address);
while (true)
{
rng1 = rng.FindNext(rng1);
if (rng1 == null)
return i;
Console.WriteLine(rng1.Address);
if (rng1.Address == address)
return i;
else
i++;
}
}
}
}
You have to use Microsoft.Office.Interop.Excel in your C# code then the below source code will search in first row for the Excel sfilename is filename
int countOccurence = 0;
public bool SearchRows(string valTosearch)
{
Excel.Application xlApp = new Excel.Application();
xlApp.ScreenUpdating = false;
try
{
xlApp.DisplayAlerts = false;
vk_filename = SFileName;
//Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(SFileName);
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(
SFileName, vk_update_links, vk_read_only,
vk_format, vk_password,
vk_write_res_password,
vk_ignore_read_only_recommend, vk_origin,
vk_delimiter, vk_editable, vk_notify,
vk_converter, vk_add_to_mru,
vk_local, vk_corrupt_load);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
// loop trough cell range and excel rows below will search in 1st row
Excel.Worksheet worksheet = xlRange.Worksheet;
for (int iCount = 1; iCount <= colCount; iCount++)
{
string cellValue = "";
string fldValue = "";
Microsoft.Office.Interop.Excel.Range fldRange = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, iCount];
if (fldRange.Value2 != null)
{
fldValue = fldRange.Value2.ToString().Trim().ToLower();
}
else
{
fldValue = null;
}
Microsoft.Office.Interop.Excel.Range CellRange = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[2, iCount];
if (CellRange.Value2 != null)
{
cellValue = CellRange.Value2.ToString().Trim().ToLower();
if (cellvalue == valtosearch)
{
countOccurence +=1;
}
}
else
{
cellValue = null;
}
}
xlWorkbook.Close(vk_save_changes, vk_filename, vk_route_workbook);
//xlWorkbook.Save();
xlApp.Quit();
return true;
}
catch
{
xlApp.Quit();
return false;
}
}

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