Problem with closing excel by c# - c#

I've got unit test with this code:
Excel.Application objExcel = new Excel.Application();
Excel.Workbook objWorkbook = (Excel.Workbook)(objExcel.Workbooks._Open(#"D:\Selenium\wszystkieSeba2.xls", true,
false, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value));
Excel.Worksheet ws = (Excel.Worksheet)objWorkbook.Sheets[1];
Excel.Range r = ws.get_Range("A1", "I2575");
DateTime dt = DateTime.Now;
Excel.Range cellData = null;
Excel.Range cellKwota = null;
string cellValueData = null;
string cellValueKwota = null;
double dataTransakcji = 0;
string dzien = null;
string miesiac = null;
int nrOperacji = 1;
int wierszPoczatkowy = 11;
int pozostaƂo = 526;
cellData = r.Cells[wierszPoczatkowy, 1] as Excel.Range;
cellKwota = r.Cells[wierszPoczatkowy, 6] as Excel.Range;
if ((cellData != null) && (cellKwota != null))
{
object valData = cellData.Value2;
object valKwota = cellKwota.Value2;
if ((valData != null) && (valKwota != null))
{
cellValueData = valData.ToString();
dataTransakcji = Convert.ToDouble(cellValueData);
Console.WriteLine("data transakcji to: " + dataTransakcji);
dt = DateTime.FromOADate((double)dataTransakcji);
dzien = dt.Day.ToString();
miesiac = dt.Month.ToString();
cellValueKwota = valKwota.ToString();
}
}
r.Cells[wierszPoczatkowy, 8] = "ok";
objWorkbook.Save();
objWorkbook.Close(true, #"C:\Documents and Settings\Administrator\Pulpit\Selenium\wszystkieSeba2.xls", true);
objExcel.Quit();
Why after finish test I'm still having excel in process (it does'nt close)
And : is there something I can improve to better perfomance ??
Excel 2007 and .net 3.5

I use a code segment like this to forcefully close it:
public void DisposeExcelInstance()
{
//oXL.DisplayAlerts = false;
//oWB.Close(null, null, null);
//oXL.Quit();
//oWB.Close(null, null, null);
//oXL.Quit();
///KNG - CLEANUP code
oXL.DisplayAlerts = false;
oWB.Close(null, null, null);
oXL.Workbooks.Close();
oXL.Quit();
if (oResizeRange != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oResizeRange);
if (oSheet != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
if (oWB != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
if (oXL != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.Collect(); // force final cleanup!
}

Maybe ur reference count is off:
http://support.microsoft.com/kb/317109

In addition to Kangkan's answer, you can also try to use an existing Excel instance (if there is still an unclosed instance running):
try {
objExcel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
} catch (Exception) {
if (objExcel == null) {
objExcel = new Excel.Application();
}
}

try something not using Excel automation:
How can I create an Excel compatible Spreadsheets on the server side in C#?

Related

C# Excel process won't close

I'm writing a program where you can enter stuff into an excel via a button.
When the button is pressed the Application is started it interacts with the spreadsheet.
But when it's finished interacting the process should be closed completely but it hangs in the Task Manager.
I've tried numerous solutions to close it but it won't.
Here is my code
using Microsoft.Office.Interop.Excel;
using System.Linq;
using System.Runtime.InteropServices;
using Application = Microsoft.Office.Interop.Excel.Application;
.
.
.
.
Application oxl = null;
Workbooks wbs = null;
Workbook wb = null;
Worksheet ws = null;
Sheets wss = null;
Range r = null;
Range orange2 = null;
Range resultRange = null;
try {
oxl = new Application();
wbs = oxl.Workbooks;
wb = wbs.Open(Settings.Default.excelPath);
wss = wb.Worksheets;
ws = (Worksheet) wss[2];
r = ws.Range["A2:A924"];
foreach(string tofind in tofinds) {
resultRange = null;
string[] s = data[tofind];
resultRange = r.Find(
What: tofind,
LookIn: XlFindLookIn.xlValues,
LookAt: XlLookAt.xlPart,
SearchOrder: XlSearchOrder.xlByRows,
SearchDirection: XlSearchDirection.xlPrevious,
MatchCase: true);
if (resultRange != null) {
int i = resultRange.Row;
orange2 = ws.Cells[i, 2];
if (orange2.Value == null) {
orange2 = ws.Cells[i, 2];
//s[0]= -3.94e6
orange2.Value = s[0].Split((char)
'e')[0].Replace("-", "");
orange2.NumberFormat = "0.00";
}
} else {
//Log to Console
}
}
wb.Save();
} catch (IOException e) {
Console.WriteLine(e.Message);
} finally {
Marshal.FinalReleaseComObject(orange2);
Marshal.FinalReleaseComObject(r);
Marshal.FinalReleaseComObject(resultRange);
orange2 = null;
r = null;
resultRange = null;
foreach(Worksheet sheet in wss) {
Marshal.FinalReleaseComObject(sheet);
}
Marshal.FinalReleaseComObject(wss);
wss = null;
wb.Close(0);
wbs.Close();
foreach(Workbook workbook in wbs) {
Marshal.FinalReleaseComObject(workbook);
}
Marshal.FinalReleaseComObject(wb);
wb = null;
Marshal.FinalReleaseComObject(wbs);
wbs = null;
oxl.Application.Quit();
oxl.Quit();
Marshal.FinalReleaseComObject(oxl);
oxl = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Final");
}
Found the Solution.
If you get your Range by
Range r = sheet.Cells[1,1];
Marshal.FinalReleaseComObject(r);
r = null;
Cells[1,1] creates an own COM object
Rang r1 = sheet.Cells;
Range r = r1[1,1];
Marshal.FinalReleaseComObject(r1);
r1 = null;
Marshal.FinalReleaseComObject(r1);
r1 = null;
by doing that it worked for me

C# Excel Write to multiple cells

Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.
This is my little method:
public void writeExcelFile()
{
string path = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, 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 = (Excel.Worksheet)mWorkSheets.get_Item(1);
//Excel.Range range = mWSheet1.UsedRange;
//int colCount = range.Columns.Count;
//int rowCount = range.Rows.Count;
int countRows = mWSheet1.UsedRange.Rows.Count;
int countColumns = mWSheet1.UsedRange.Columns.Count;
object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[countRows + index, 1] = countRows + index;
mWSheet1.Cells[countRows + index, 2] = "test" + index;
}
//Excel.Worksheet sheet = workbook.ActiveSheet;
//Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);
mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, 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();
}
I tried it with get_range but i get an exception that this is not aviable.
It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.
Thanks for your Time and sorry for my english.
EDIT: At least the read process works now and i loop trough a selected range.
Here is the working code:
public void writeExcelFile()
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open the Excel File
Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);
String SheetName = "Gesamt";
Excel._Worksheet oSheet = oWB.Sheets[SheetName];
String start_range = "B4";
String end_range = "R81";
Object[,] values = oSheet.get_Range(start_range, end_range).Value2;
int t = values.GetLength(0);
for (int i = 1; i <= values.GetLength(0); i++)
{
String val = values[i, 1].ToString();
}
oXL.Quit();
}
After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.
the code:
public void writeExcelFile()
{
try
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a Excel File
Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
Excel._Worksheet oSheet = oWB.ActiveSheet;
List<String> Name = new List<String>();
List<Double> Percentage = new List<Double>();
Name.Add("Anil");
Name.Add("Vikas");
Name.Add("Ashwini");
Name.Add("Tobias");
Name.Add("Stuti");
Name.Add("Raghavendra");
Name.Add("Chithra");
Name.Add("Glen");
Name.Add("Darren");
Name.Add("Michael");
Percentage.Add(78.5);
Percentage.Add(65.3);
Percentage.Add(56);
Percentage.Add(56);
Percentage.Add(97);
Percentage.Add(89);
Percentage.Add(85);
Percentage.Add(76);
Percentage.Add(78);
Percentage.Add(89);
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
//Enter the Header data in Column A
int i = 0;
for (i = 0; i < Name.Count; i++)
{
oSheet.Cells[i + 2, 1] = Name[i];
}
//Enter the Percentage data in Column B
for (i = 0; i < Percentage.Count; i++)
{
oSheet.Cells[i + 2, 2] = Percentage[i];
}
oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
//Obtain the Average of the Percentage Data
string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
//String ReportFile = #"D:\Excel\Output.xls";
oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
Type.Missing, Type.Missing,
false,
false,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is not my own code its from a blog: the blog where i got it just edited so it works for me.

written code for Autofit in c# for Excel sheet. Everything is perfect. but the Excel.exe is still running even after clearing com componets

This is my code. I am trying to export gridview to excel with some of the cells with color and autofit. The problem here is everything is working fine except the EXCEL.EXE running in the background. But If i exclude code for Autofit and coloring cells, then the Excel Task is terminated.
Below is my code
protected void xlsWorkBook()
{
try
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Workbooks oWBs;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWBs = oXL.Workbooks;
oWB = oWBs.Add(1);
oSheet = oWB.ActiveSheet;
DataGridView dataGridExport = new DataGridView();
dataGridExport.DataSource = GetData();
bool isColorCells = false;
oRange = oSheet.Cells;
for (int k = 1; k <= dataGridExport.Columns.Count; k++)
{
//oRange.set_Item(1, k, dataGridExport.Columns[k - 1].Name);
oSheet.Cells[1, k] = dataGridExport.Columns[k - 1].Name;
((dynamic)oSheet.Cells[1, k]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SteelBlue);
}
for (int i = 1; i <= dataGridExport.Rows.Count; i++)
{
for (int k = 1; k <= dataGridExport.Rows[i - 1].Cells.Count; k++)
{
if (Convert.ToString(dataGridExport.Rows[i - 1].Cells[k - 1].Value) != string.Empty)
{
//oRange.set_Item(i + 1, k, dataGridExport.Rows[i - 1].Cells[k - 1].Value);
oSheet.Cells[i + 1, k] = dataGridExport.Rows[i - 1].Cells[k - 1].Value;
}
if ((isColorCells) && (dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb() != 0))
{
//oRange.Interior.Color = Color.Red;
((dynamic)oSheet.Cells[i + 1, k]).Interior.Color = ColorTranslator.ToOle(Color.FromArgb(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb()));
}
}
}
dataGridExport = null;
oSheet.Columns.AutoFit();
//oRange.EntireColumn.AutoFit();
// Save the sheet and close
//oSheet = null;
//oRange = null;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xlsx";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
oWB.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
}
GC.Collect();
GC.WaitForPendingFinalizers();
oWB.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWBs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
this.Cursor = Cursors.Default;
}
Moving Range to different function solved my problem. The Excel.exe is not running at the background anymore. But i am not sure why. Somebody can give explanation for this?
protected void xlsWorkBook()
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
// 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.Value);
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
UpdataDataToExcelSheets(oSheet,"sheet name",dataGrid1,true);
// Save the sheet and close
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xlsx";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
oWB.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
}
oWB.Close();
oXL.Quit();
//// Clean up
if (oSheet != null)
{
Marshal.FinalReleaseComObject(oSheet);
oSheet = null;
}
if (oWB != null)
{
Marshal.FinalReleaseComObject(oWB);
oWB = null;
}
if (oXL.Workbooks != null)
{
Marshal.FinalReleaseComObject(oXL.Workbooks);
}
if (oXL != null)
{
Marshal.FinalReleaseComObject(oXL);
oXL = null;
}
//// NOTE: When in release mode, this does the trick
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void UpdataDataToExcelSheets(Excel.Worksheet oSheet,string sheetName, DataGridView dataGridExport,bool isColorCells)
{
Excel.Range oRange;
oSheet.Name = sheetName;
for (int k = 1; k <= dataGridExport.Columns.Count; k++)
{
oSheet.Cells[1, k] = dataGridExport.Columns[k - 1].Name;
((dynamic)oSheet.Cells[1, k]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SteelBlue);
}
for (int i = 1; i <= dataGridExport.Rows.Count; i++)
{
for (int k = 1; k <= dataGridExport.Rows[i - 1].Cells.Count; k++)
{
if (Convert.ToString(dataGridExport.Rows[i - 1].Cells[k - 1].Value) != string.Empty)
{
oSheet.Cells[i + 1, k] = dataGridExport.Rows[i - 1].Cells[k - 1].Value;
}
if ((isColorCells)&&(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb() != 0))
{
((dynamic)oSheet.Cells[i + 1, k]).Interior.Color = ColorTranslator.ToOle(Color.FromArgb(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb()));
}
}
}
oRange = oSheet.Range[oSheet.Cells[1, 1],
oSheet.Cells[dataGridExport.Rows.Count - 1, dataGridExport.Columns.Count + 1]];
oRange.EntireColumn.AutoFit();
if (oRange != null)
{
Marshal.FinalReleaseComObject(oRange);
oRange = null;
}
}

C# Interop print and close Excel file

have problem with interop and editing existing excel file. Excel app doesn't want to close. If I set code, when I edit cells, as comment, rest of code work as I need - Excel open and after print dialog close.
Excel.Application excelApp = null;
Excel.Workbook excelWorkbook = null;
Excel.Worksheet excelWorksheet = null;
string workbookPath = "";
if (RBType1.Checked == true) { workbookPath = Path.GetFullPath("Excel/Mesto.xls"); }
else if (RBType2.Checked == true) { workbookPath = Path.GetFullPath("Excel/Ulehly.xls"); }
else if (RBType3.Checked == true) { workbookPath = Path.GetFullPath("Excel/Spolecenstvi.xls"); }
else if (RBType4.Checked == true) { workbookPath = Path.GetFullPath("Excel/Vlastnici.xls"); }
excelApp = new Excel.Application();
excelApp.Visible = true;
excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(1);
excelWorksheet.Cells[4, "J"] = RequisitionNumberBox.Text;
excelWorksheet.Cells[9, "C"] = ApplicantBox.Text;
excelWorksheet.Cells[9, "G"] = StreetBox.Text;
excelWorksheet.Cells[9, "J"] = CPBoxC.Text;
excelWorksheet.Cells[10, "J"] = CBBox.Text;
excelWorksheet.Cells[11, "D"] = CTBox.Text;
excelWorksheet.Cells[11, "G"] = ContactPersonBox.Text;
excelWorksheet.Cells[14, "B"] = RepairBox.Text;
excelWorksheet.Cells[20, "B"] = ItemBox.Text;
if (PMOption1.Checked == true) { excelWorksheet.Cells[23, "D"] = "X"; }
if (PMOption2.Checked == true) { excelWorksheet.Cells[24, "D"] = "X"; }
excelWorksheet.Cells[23, "F"] = IssueDate.Text;
excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrint].Show();
excelWorkbook.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
releaseObject(excelWorksheet);
releaseObject(excelWorkbook);
releaseObject(excelApp);
releaseObject code (found this on internet)
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();
}
How I should edit this code, that it close Excel when program edits cells?

Read all the cell values from an Excel range in C#

Suppose I have range from E2 to E16. How do I read values from cells E2 to E16?
You can try somethinfg like this. it should work
U can specify ur range as u wish inside.
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
}
}
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i-1] = "";
else
theArray[i-1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
Another Alternative approach. Positng as a spearate answer because it wil be give less space for confusion.
Excel.Application app = new Excel.Application();
Excel.Workbook wbook = null;
Excel.Worksheet wsheet = null;
Excel.Range range = null;
app.Visible = false;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string filepath = inputFile1.Value.ToString();
if (filepath != "")
{
wbook = app.Workbooks.Open(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);
string currentSheet = "Sheet1";
wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(currentSheet);
range = wsheet.get_Range("B6", "H20");
System.Array myvalues = (System.Array)range.Cells.Value2;
valueArray = ConvertToStringArray(myvalues);
if (app != null)
{
app.Workbooks.Close();
app.Quit();
}
app = null;
wsheet = null;
range = null;
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i-1] = "";
else
theArray[i-1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}

Categories

Resources