C# Struggling to read excel data into arrays (interop) - c#

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.

Related

Select column by header text and check if rest of column is empty, delete if empty?

I have an excel sheet with a similar format to the table below, if I know the column header text "Col2" how can I then check all the cells in that column only are empty or not and delete the entire column if they are?
*Col1 * Col2 * Col3*
********************
*Val * * Val *
*Val * * Val *
I think I need to select the headers in a range and find the index of the column with a header that matches the string in question and I also need to use CountA to count the not empty cells? I think there's also a step in the middle missing to select the column for CountA, then I need to delete if there are 0 not empty cells.
My working code below to open the worksheet and resize the columns:
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelBooks = excelApp.Workbooks;
excelBook = excelBooks.Open("test.csv", 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);
excelSheet = excelBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
excelCols = excelSheet.Columns;
i = 1;
while (i < colCount) {
excelCol = excelCols[i] as Microsoft.Office.Interop.Excel.Range;
excelCol.AutoFit();
}
//range for first row
excelRows = excelSheet.Rows;
excelRow = excelRows[1] as Microsoft.Office.Interop.Excel.Range;
Can someone please help with this, I tried many times but I'm not totally sure how to proceed from here.
First of all, add the following using directive to the top of your file:
using Microsoft.Office.Interop.Excel;
Assuming your column headers are in row 1, you could use the following method:
static void DeleteColumnIfEmpty(Worksheet wkst, int colNo)
{
for (int i = 2; i <= wkst.UsedRange.Rows.Count; i++)
{
if (wkst.Cells[i, colNo].Value2 != null) return;
}
wkst.Columns[colNo].Delete();
}
And call it like this:
i = 1;
while (i < colCount)
{
excelCol = excelCols[i] as Range;
excelCol.AutoFit();
if (excelSheet.Cells[1, i].Value2 == "Col2")
DeleteColumnIfEmpty(excelSheet, i);
}

Read Excel all columns as string in C#

I am trying to read Excel columns as string in C#. I wrote following code:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:\\excelFile.xls;"
+ "Extended Properties=\"Excel 8.0;IMEX=1\"";
The problem is that in one column I have mixed data type like numbers,strings. I already
searched for solutions, but none was helpful for me. The link bellow didn't help me(
https://stackoverflow.com/questions/11200472/read-excel-columns-as-text
I found that Excel decide which type will be column according to top 10 columns.How can I fix this issue?I am using Microsoft.Office.Interop.Excel.
Take a look at this on codeproject. As stated in the comments, if you're using Interop you don't need a connection string. You can simply open a workbook, get an array of the items (an object array) and call ToString() on each item to get its string representation. Something like this should do:
ApplicationClass app = new ApplicationClass();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
Workbook book = app.Workbooks.Open(#"path\Book1.xls",
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);
Worksheet sheet = (Worksheet)book.Worksheets[1];
Range range = sheet.get_Range(...);
string execPath = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().CodeBase);
object[,] values = (object[,])range.Value2;
for (int i = 1; i <= values.GetLength(0); i++)
{
for (int j = 1; j <= values.GetLength(1); j++)
{
string s = values[i, j].ToString();
}
}
What I usually do is that:
Range FirstCell = YourWorkSheet.Range["A1"]; //Use the Header of the column you want instead of "A1", or even a name you give to the cell in the worksheet.
List<string> ColumnValues = new List<string>();
int i = 1;
object CellValue = FirstCell.Offset[i, 0].Value;
while (CellValue != null)
{
ColumnValues.Add(CellValue.ToString());
i++;
CellValue = FirstCell.Offset[i,0].Value;
}
Hmm. Don't know if it helps, but I had the same issue. Now it works for me with the following connection string:
<add name="Excel2010File"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties="Excel 12.0;READONLY=TRUE;IMEX=1""
providerName="Microsoft.ACE.OLEDB.12.0" />
You can find the libraries for my provider in the web (sorry, don't have a link anymore) if you don't have it. And you can set it to 12.0 even with a lower versioned excel file.

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 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.

C#: How to access an Excel cell?

I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.
Currently I am at this stage with the following code but still I am getting errors:
Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
// is there already such a file ?
if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
{
// then go and load this into excel
Microsoft.Office.Interop.Excel.Workbooks.Open(
"C:\\csharp\\errorreport1.xls", true, false,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
else
{
// if not go and create a workbook:
newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
(Microsoft.Office.Interop.Excel._Worksheet)
newWorkBook.Worksheets.get_Item(1);
}
i++;
j = 1;
j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
+ rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";
These are the top 2 errors I am getting:
Error 1 An object reference is required for the nonstatic field, method, or
property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
object, object, object, object, object, object, object, object, object,
object, object, object, object)'
Error 2 The name 'newWorkbook' does not exist in the current context
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)
Check this out, it should get you started,
http://www.codeproject.com/KB/office/package.aspx
And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.
Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;
if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}
You can also do
Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;
if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}
And if you need to insert rows/columns
// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
I think, that you have to declare the associated sheet!
Try something like this
objsheet(1).Cells[i,j].Value;
How I work to automate Office / Excel:
Record a macro, this will generate a VBA template
Edit the VBA template so it will match my needs
Convert to VB.Net (A small step for men)
Leave it in VB.Net, Much more easy as doing it using C#
Try:
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();
oSheet.Cells[3, 9] = "Some Text"
Simple.
To open a workbook.
Use xlapp.workbooks.Open()
where you have previously declared and instanitated xlapp as so..
Excel.Application xlapp = new Excel.Applicaton();
parameters are correct.
Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.
This works fine for me
Excel.Application oXL = null;
Excel._Workbook oWB = null;
Excel._Worksheet oSheet = null;
try
{
oXL = new Excel.Application();
string path = #"C:\Templates\NCRepTemplate.xlt";
oWB = oXL.Workbooks.Open(path, 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows, "", true, false,
0, true, false, false);
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[2, 2] = "Text";
You can use the below code; it's working fine for me:
newWorkbook = appExcel.Workbooks.Add();

Categories