Read all the cell values from an Excel range in C# - 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;
}

Related

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;
}
}

Setting border property in excel using c# is not working in case of multiple excel file

I am designing a small program using Microsoft.Office.Interop.Excel library in c#. My program read the excel files(whose names are 1.xlss,2.xlsx and so on) and make a new excel file and then copy the data of all excel files into new excel files with one line gap. I also set the certain property like border,font,backgroundcolor etc of the cells.
Everything is fine for first excel file(1.xls) but in case of 2nd,3rd and so on, It's not setting the border property of the cells.Here is my code
// data member initialization for reading the sheet
Excel.Application app;
Excel.Workbook workbook;
Excel.Worksheet worksheet;
Excel.Range range;
// data member initialization for writing sheet
Excel.Application finalApp;
Excel.Workbook finalWorkBook;
Excel.Worksheet finalWorkSheet;
String path = this.textBox1.Text;
String numberOfFiles = (String)this.comboBox1.SelectedItem;
int count = 1;
int row = 1, col = 1;
try
{
// Object creation for the final sheet
finalApp = new Excel.ApplicationClass();
finalApp.Visible = true;
finalWorkBook = finalApp.Workbooks.Add(1);
finalWorkSheet = (Excel.Worksheet)finalWorkBook.Sheets[1];
// opening a excel file
app = new Excel.ApplicationClass();
Excel.Borders b=null;
Excel.Borders fb = null;
try
{
for (int k = 0; k < Int32.Parse(numberOfFiles); k++)
{
fullPath = #path + #"\" + count + ".xlsx";
workbook = app.Workbooks.Open(fullPath, 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 = (Excel.Worksheet)workbook.Sheets.get_Item(1);
range = worksheet.UsedRange;
int cnum1 = range.Columns.Count;
int rnum1 = range.Rows.Count;
int i, j;
for (i = 1; i <= rnum1; i++)
{
for (j = 1; j <= cnum1; j++)
{
if ((range.Cells[i, j] as Excel.Range).Value2 != null)
{
string value1 = (range.Cells[i, j] as Excel.Range).Value2.ToString();
finalWorkSheet.Cells[row, col] = value1;
b= (Excel.Borders)(range.Cells[i, j] as Excel.Range).Borders;
//MessageBox.Show(b.Weight.ToString());
fb=(finalWorkSheet.Cells[i, j] as Excel.Range).Borders;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight= b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Weight = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Weight;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle;
fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle;
//fb.Color = b.Color;
//(finalWorkSheet.Cells[i, j] as Excel.Range).BorderAround(b.LineStyle,(Excel.XlBorderWeight)b.Weight,
//(Excel.XlColorIndex)b.ColorIndex,b.Color);
}
(finalWorkSheet.Cells[row, col] as Excel.Range).Interior.Color = (range.Cells[i, j] as Excel.Range).Interior.Color;
(finalWorkSheet.Cells[row, col] as Excel.Range).Font.Color = (range.Cells[i, j] as Excel.Range).Font.Color;
col++;
}
row++;
col = 1;
}
//finalWorkBook.SaveAs("hello.xlsx", Excel.XlFileFormat.xlExcel4Workbook, Missing.Value,
//Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value,
//Missing.Value, Missing.Value, Missing.Value);
workbook.Close(false, false, Missing.Value);
count++;
row++;
col = 1;
}
}
catch (FileNotFoundException fnfe)
{
MessageBox.Show("Error while opening the file "+fullPath);
}
//finalWorkBook.Close(true,false,Missing.Value);
}
catch (Exception ex)
{
MessageBox.Show(#"Some Error has occurred.Please check the path Correctly
whether it's correct or not");
}
}
Any help would be appreciated.
fb=(finalWorkSheet.Cells[i, j] as Excel.Range).Borders;
Should be
fb=(finalWorkSheet.Cells[row, col] as Excel.Range).Borders;

access string in worksheet cell with Excel.Worksheet?

How do I access the string value in a cell in an Excel worksheet?
string cellInfo = (string)w.Cells[3, 3];
I want the string value in the 3rd row, 3rd column, C3
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Open(string.Format(#"{0}\{1}", Directory.GetCurrentDirectory(), excelFilename),
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);
List<Excel.Worksheet> result = excel.Worksheets.Cast<Excel.Worksheet>().Where(w => !exclude.Contains(w.Name)).ToList();
result.ForEach(w => {
Excel.Range objRange = w.get_Range("C3", "C3");
string colLengthStr = objRange.Value2;
}
There are many answers on SO about how to get data from Excel using c#. But you will need to do something similar to this:
Excel.Range objRange = (Excel.Range)objSheet.Cells[1,1];
strData = objRange.get_Value(Missing.Value).ToString();
How to read data of an Excel file using C#?
Resources for learning c# Excel interop
Or
C# Excel Interop
Or Even
How to automate Excel from C#.NET
Code from the automate Excel from c#.net, which includes reading/writing to cells:
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5,2];
saNames[ 0, 0] = "John";
saNames[ 0, 1] = "Smith";
saNames[ 1, 0] = "Tom";
saNames[ 1, 1] = "Brown";
saNames[ 2, 0] = "Sue";
saNames[ 2, 1] = "Thomas";
saNames[ 3, 0] = "Jane";
saNames[ 3, 1] = "Jones";
saNames[ 4, 0] = "Adam";
saNames[ 4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
//Manipulate a variable number of columns for Quarterly Sales Data.
DisplayQuarterlySales(oSheet);
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
MessageBox.Show( errorMessage, "Error" );
}
}
private void DisplayQuarterlySales(Excel._Worksheet oWS)
{
Excel._Workbook oWB;
Excel.Series oSeries;
Excel.Range oResizeRange;
Excel._Chart oChart;
String sMsg;
int iNumQtrs;
//Determine how many quarters to display data for.
for( iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)
{
sMsg = "Enter sales data for ";
sMsg = String.Concat( sMsg, iNumQtrs );
sMsg = String.Concat( sMsg, " quarter(s)?");
DialogResult iRet = MessageBox.Show( sMsg, "Quarterly Sales?",
MessageBoxButtons.YesNo );
if (iRet == DialogResult.Yes)
break;
}
sMsg = "Displaying data for ";
sMsg = String.Concat( sMsg, iNumQtrs );
sMsg = String.Concat( sMsg, " quarter(s)." );
MessageBox.Show( sMsg, "Quarterly Sales" );
//Starting at E1, fill headers for the number of columns selected.
oResizeRange = oWS.get_Range("E1", "E1").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";
//Change the Orientation and WrapText properties for the headers.
oResizeRange.Orientation = 38;
oResizeRange.WrapText = true;
//Fill the interior color of the headers.
oResizeRange.Interior.ColorIndex = 36;
//Fill the columns with a formula and apply a number format.
oResizeRange = oWS.get_Range("E2", "E6").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Formula = "=RAND()*100";
oResizeRange.NumberFormat = "$0.00";
//Apply borders to the Sales data and headers.
oResizeRange = oWS.get_Range("E1", "E6").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;
//Add a Totals formula for the sales data and apply a border.
oResizeRange = oWS.get_Range("E8", "E8").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Formula = "=SUM(E2:E6)";
oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).LineStyle
= Excel.XlLineStyle.xlDouble;
oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).Weight
= Excel.XlBorderWeight.xlThick;
//Add a Chart for the selected data.
oWB = (Excel._Workbook)oWS.Parent;
oChart = (Excel._Chart)oWB.Charts.Add( Missing.Value, Missing.Value,
Missing.Value, Missing.Value );
//Use the ChartWizard to create a new chart from the selected data.
oResizeRange = oWS.get_Range("E2:E6", Missing.Value ).get_Resize(
Missing.Value, iNumQtrs);
oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value );
oSeries = (Excel.Series)oChart.SeriesCollection(1);
oSeries.XValues = oWS.get_Range("A2", "A6");
for( int iRet = 1; iRet <= iNumQtrs; iRet++)
{
oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
String seriesName;
seriesName = "=\"Q";
seriesName = String.Concat( seriesName, iRet );
seriesName = String.Concat( seriesName, "\"" );
oSeries.Name = seriesName;
}
oChart.Location( Excel.XlChartLocation.xlLocationAsObject, oWS.Name );
//Move the chart so as not to cover your data.
oResizeRange = (Excel.Range)oWS.Rows.get_Item(10, Missing.Value );
oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;
oResizeRange = (Excel.Range)oWS.Columns.get_Item(2, Missing.Value );
oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
}
Based on your edit try the following:
result.ForEach(w => {
Excel.Range objRange = w.get_Range("C3", Missing.Value);
string colLengthStr = objRange.Value2;
}

Problem with closing excel by 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#?

Categories

Resources