public variable's reference getting lost in c# - c#

inside my class i am declaring
public Excel.Range range { get; set; }
the constructor of the class calls this method:
private void OpenWorkBook()
{
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(MasterFileName, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
}
after that when i reference range from a different method:
public void CreateFiles(string column)
{
try
{
var valueRange = range.get_Range(column + "3", column + range.Rows.Count.ToString());
var deleteRange = range;
i am getting:
valueRange threw an exception of type System.Runtime.InteropServices.InvalidComObjectException'
does anyone know why i am losing the contents of this variable?
here's my full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace EmailSalesVolumeSolution
{
class WorkBook
{
public string MasterFileName { get; set; }
public string[] DistinctEmails { get; set; }
public Excel.Application xlApp {get;set;}
public Excel.Workbook xlWorkBook { get; set; }
public Excel.Worksheet xlWorkSheet { get; set; }
public Excel.Range range { get; set; }
private void OpenWorkBook()
{
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(MasterFileName, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
}
public WorkBook(string filename)
{
MasterFileName = filename;
//xlWorkBook = null;
//xlApp = null;
//xlWorkSheet = null;
//range = null;
OpenWorkBook();
}
public void SendEmail()
{
}
public void CreateFiles(string column)
{
try
{
var valueRange = range.get_Range(column + "3", column + range.Rows.Count.ToString());
var deleteRange = range;
string cell = "";
DistinctEmails = DistinctValues(valueRange);
foreach (string email in DistinctEmails)
{
for (int rCnt = 2; rCnt <= valueRange.Rows.Count; rCnt++)
{
cell = (string)(valueRange.Cells[rCnt, 1] as Excel.Range).Value2;
if (cell == null || cell != email)
{
deleteRange=xlWorkSheet.get_Range(column + rCnt.ToString() + ":" + column + rCnt.ToString(), Type.Missing);
deleteRange.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
}
}
xlWorkBook.SaveAs(xlWorkBook.Path + #"\" + email, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
//DisposeMe();
// Release all COM RCWs.
// The "releaseObject" will just "do nothing" if null is passed,
// so no need to check to find out which need to be released.
// The "finally" is run in all cases, even if there was an exception
// in the "try".
// Note: passing "by ref" so afterwords "xlWorkSheet" will
// evaluate to null. See "releaseObject".
releaseObject( xlWorkSheet);
releaseObject( xlWorkBook);
// The Quit is done in the finally because we always
// want to quit. It is no different than releasing RCWs.
if (xlApp != null)
{
xlApp.Quit();
}
releaseObject( xlApp);
}
}
private string[] DistinctValues(Excel.Range EmailList)
{
string cell = "";
List<string> emails = new List<string>();
for (int rCnt = 1; rCnt <= EmailList.Rows.Count; rCnt++)
{
cell = (string)(EmailList.Cells[ rCnt,1] as Excel.Range).Value2;
if (cell!=null)
emails.Add(cell.ToString());
}
releaseObject(EmailList);
return emails.Distinct().ToArray();
}
private void releaseObject( object obj) // note ref!
{
// Do not catch an exception from this.
// You may want to remove these guards depending on
// what you think the semantics should be.
if (obj != null && Marshal.IsComObject(obj))
{
Marshal.ReleaseComObject(obj);
}
// Since passed "by ref" this assingment will be useful
// (It was not useful in the original, and neither was the
// GC.Collect.)
obj = null;
}
private void DisposeMe()
{
// Cleanup:
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlWorkSheet);
xlWorkBook.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkBook);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
}
}
}
here's how i instantiate the class!!
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
InitializeWorkBook(openFileDialog1.FileName);
}
private void InitializeWorkBook(string filename)
{
WorkBook wb= new WorkBook(filename);
wb.CreateFiles("A");
}

Related

Reading Cell Value of Excel in C#, null reference exception

I am trying to read the cell value from an Excel sheet, and used Value and Value2 to see the Cell value. It keeps throwing "System.NullReferenceException: 'Object reference not set to an instance of an object.'" Error. I am unable to figure out where is the issue in code.
I know the file path and the Excel sheet it's reading is correct.
public String readEDriver()
{
int nRows = 1;
int nCols = 1;
String driverLoc = null;
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
Workbook excelWorkbook;
excelWorkbook = excelApp.Workbooks.Open("C:\\A\\Config.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet excelWorksheet;
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[1];
excelWorksheet.Activate();
String eName =excelWorksheet.Name;
if (excelWorksheet == null)
{
throw new Exception(string.Format("Named worksheet ({0}) not found.", excelWorksheet));
}
else
{
var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
if (excelWorksheet.Cells[nRows,nCols]!=null)
{
cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
driverLoc = cellVal.ToString();
}
}
excelWorkbook.Close();
excelApp.Quit();
}
return driverLoc;
}
it breaks at the
var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
It fails to retrieve the Excel Range and gives NullReferenceException
Message:
System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
I tried your code because it seemed OK.
It works for me with a couple of minor compiling topics:
1.- Use "/" instead od "\" for the paths. Windows doesn´t like those.
2.- I had to add the Excel.Workbook and Excel.Worksheet because the compiler warned me
Apart from that it works. Below your code with my slight corrections.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string aux = readEDriver();
Console.WriteLine(aux);
Console.ReadLine();
}
public static string readEDriver()
{
int nRows = 1;
int nCols = 1;
String driverLoc = null;
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
Excel.Workbook excelWorkbook;
excelWorkbook = excelApp.Workbooks.Open("C:/Users/Usuario/Desktop/PruebasTxtFile.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet excelWorksheet;
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[1];
excelWorksheet.Activate();
String eName = excelWorksheet.Name;
if (excelWorksheet == null)
{
throw new Exception(string.Format("Named worksheet ({0}) not found.", excelWorksheet));
}
else
{
var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
if (excelWorksheet.Cells[nRows, nCols] != null)
{
cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
driverLoc = cellVal.ToString();
}
}
excelWorkbook.Close();
excelApp.Quit();
}
return driverLoc;
}
}
}
Hope that helps!

Release Interop Excel object

I'm currently writting a C#.NET application who use a VBA macro in an Excel file.
I run the macro from the c# application when the user click on a button. I have to wait all data are downloaded that's why this is the VBA code who execute "Application.Quit".
There is my code :
private void toolStripButton5_Click(object sender, EventArgs e)
{
int lastUsedRowFund, lastUsedRowEquity, lastUsedRowBond, lastUsedRowAccount = 0;
Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook oWB = null;
Excel.Worksheet oSheetFund = null;
Excel.Worksheet oSheetEquity = null;
Excel.Worksheet oSheetBond = null;
Excel.Worksheet oSheetAccount = null;
oXL.Visible = false;
oWB = oXL.Workbooks.Open("C:\\extract.xlsm");
oSheetFund = oWB.Sheets["Fund"];
oSheetEquity = oWB.Sheets["Equity"];
oSheetBond = oWB.Sheets["Bond"];
oSheetAccount = oWB.Sheets["Account"];
string[] valuesHeaderFund = {"field1", "field2" };
string[] valuesHeaderEquity = {"field1", "field2"};
string[] valuesHeaderBond = {"field1", "field2"};
string[] valuesHeaderAccount = {"field1", "field2"};
Excel.Range headerFund = oSheetFund.get_Range("A1", "AA1");
Excel.Range headerEquity = oSheetEquity.get_Range("A1", "AE1");
Excel.Range headerBond = oSheetBond.get_Range("A1", "AE1");
Excel.Range headerAccount = oSheetAccount.get_Range("A1", "AE1");
headerFund.Value2 = valuesHeaderFund;
headerEquity.Value2 = valuesHeaderEquity;
headerBond.Value2 = valuesHeaderBond;
headerAccount.Value2 = valuesHeaderAccount;
Excel.Range lastRowFund = oSheetFund.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowEquity = oSheetEquity.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowBond = oSheetBond.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowAccount = oSheetAccount.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
lastUsedRowFund = lastRowFund.Row;
lastUsedRowEquity = lastRowEquity.Row;
lastUsedRowBond = lastRowBond.Row;
lastUsedRowAccount = lastRowAccount.Row;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string[] data = { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()};
if (row.Cells[5].Value.ToString() == "FON")
{
lastUsedRowFund += 1;
oSheetFund.get_Range("A" + lastUsedRowFund, "K" + lastUsedRowFund).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "ACT")
{
lastUsedRowEquity += 1;
oSheetEquity.get_Range("A" + lastUsedRowEquity, "K" + lastUsedRowEquity).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "OBL")
{
lastUsedRowBond += 1;
oSheetBond.get_Range("A" + lastUsedRowBond, "K" + lastUsedRowBond).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "ACCOUNT")
{
lastUsedRowAccount += 1;
oSheetAccount.get_Range("A" + lastUsedRowAccount, "K" + lastUsedRowAccount).Value2 = data;
}
}
RunMacro(oXL, new Object[] { "Main" });
oXL.UserControl = false;
//oWB.Close();
//oXL.Quit();
releaseObject(lastRowFund);
releaseObject(lastRowEquity);
releaseObject(lastRowBond);
releaseObject(lastRowAccount);
releaseObject(headerFund);
releaseObject(headerEquity);
releaseObject(headerBond);
releaseObject(headerAccount);
releaseObject(oSheetFund);
releaseObject(oSheetEquity);
releaseObject(oSheetBond);
releaseObject(oSheetAccount);
releaseObject(oWB);
releaseObject(oXL);
private void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.InvokeMethod,
null, oApp, oRunArgs);
}
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();
}
}
When i click on the toolStripButton5, everything is working. But at the end an "EXCEL.EXE" processus still alive in task manager. When i click again on the button, a new "EXCEL.EXE" is create but when the task is finish, the processus is correctly release.
When i quit my application, the first processus is release.
Can you help me to correctly release the object at the first click.
Regards,
Danny.
Unfortunatelly this is not so simple to quit Excel app, because COM objects of Interoop services still exists in memory. That's why Excel.exe process is still running. Every object can be released using Marshal class. Sample codes:
Marshal.ReleaseComObject(excelSheets); //Worksheet
Marshal.ReleaseComObject(excelSheet); //Sheet
...and so on.
Hope this helps.
Now, it works greatly. When i execute a second extraction with Excel, the first process is correctly release when the new one is created.
I just replace in "releaseObject" System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); by
Marshal.ReleaseComObject(obj);
Maybe because i use "using System.Runtime.InteropServices;" in the header.
Thanks a lot.
Regards

Writing Data to an Existing Excel File in C#

I want to write data to an existing Excel file, whilst preserving the original data.
The file has sheet1; I want to write on sheet2, then save.
The problem is that every time I save, it will create a new Excel file and overwrite the existing one.
Could anyone provide any help to keep the old data while saving?
I have the following function
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());
xlWorkBook.Close(true, misValue, misValue);
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();
}
}
}
}
This is my way to add data to existing excel file: (Its very simple and efficient)
1 - Add Microsoft.Office.Interop.Excel component as a reference to your application
You can find it in .Net FrameWork in Extensions section
2- then add:
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
3- Now I have a simple class with 3 methods (openExcel, addDataToExcel, closeExcel)
public class ExcelFile
{
private string excelFilePath = string.Empty;
private int rowNumber = 1; // define first row number to enter data in excel
Excel.Application myExcelApplication;
Excel.Workbook myExcelWorkbook;
Excel.Worksheet myExcelWorkSheet;
public string ExcelFilePath
{
get { return excelFilePath; }
set { excelFilePath = value; }
}
public int Rownumber
{
get { return rowNumber; }
set { rowNumber = value; }
}
public void openExcel()
{
myExcelApplication = null;
myExcelApplication = new Excel.Application(); // create Excell App
myExcelApplication.DisplayAlerts = false; // turn off alerts
myExcelWorkbook = (Excel.Workbook)(myExcelApplication.Workbooks._Open(excelFilePath, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value)); // open the existing excel file
int numberOfWorkbooks = myExcelApplication.Workbooks.Count; // get number of workbooks (optional)
myExcelWorkSheet = (Excel.Worksheet)myExcelWorkbook.Worksheets[1]; // define in which worksheet, do you want to add data
myExcelWorkSheet.Name = "WorkSheet 1"; // define a name for the worksheet (optinal)
int numberOfSheets = myExcelWorkbook.Worksheets.Count; // get number of worksheets (optional)
}
public void addDataToExcel(string firstname, string lastname, string language, string email, string company)
{
myExcelWorkSheet.Cells[rowNumber, "H"] = firstname;
myExcelWorkSheet.Cells[rowNumber, "J"] = lastname;
myExcelWorkSheet.Cells[rowNumber, "Q"] = language;
myExcelWorkSheet.Cells[rowNumber, "BH"] = email;
myExcelWorkSheet.Cells[rowNumber, "CH"] = company;
rowNumber++; // if you put this method inside a loop, you should increase rownumber by one or wat ever is your logic
}
public void closeExcel()
{
try
{
myExcelWorkbook.SaveAs(excelFilePath, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value); // Save data in excel
myExcelWorkbook.Close(true, excelFilePath, System.Reflection.Missing.Value); // close the worksheet
}
finally
{
if (myExcelApplication != null)
{
myExcelApplication.Quit(); // close the excel application
}
}
}
}
According to Programmatically Insert to Existing Excel File using C# by R Manimaran:
Here is the code which will do the insertion in an already exists excel file.
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public static void ReadExistingExcel()
{
string path = #"C:\Tool\Reports1.xls";
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount= range.Rows.Count;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[rowCount + index, 1] = rowCount +index;
mWSheet1.Cells[rowCount + index, 2] = "New Item"+index;
}
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
If you need to create a new Sheet use the following code.
oSheet = (Excel.Worksheet)oWB.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oSheet.Name = SheetName;
Use ClosedXml dll in my case its resolved my problem
var workbook = new XLWorkbook(fileName);
var ws1 = workbook.Worksheet(1);
var ws2 = workbook.Worksheet(2);
workBook.SaveAs(fileName);
Here is my code:
public void ExcelDataAssign(List<string> ColumnwiseData, int length, DateTime ReportDate, List<string> AmountList, List<string> PeriodDateList, int CellId)
{
int PeriodColIndex = 6, Desc1ColIndex = 14, Desc2ColIndex = 11, Desc3ColIndex = 9, PeriodDateColIndex = 7;
int PeriodRowIndex = 3, Desc1RowIndex = 1, Desc2RowIndex = 1, Desc3RowIndex = 1, PeriodDateRowIndex = 3;
string cellName = ColumnwiseData[length];
string CapitiveName = ColumnwiseData[2 * length];
string DomicileName = ColumnwiseData[3 * length];
string file = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + #"\Excel\OutputTemplate.xlsx";
string fileName = file.Replace("bin", "").Replace("Debug", "");
var workbook = new XLWorkbook(fileName);
var ws1 = workbook.Worksheet(1);
ws1.Cell(1, 2).Value = DomicileName;
ws1.Cell(2, 2).Value = CapitiveName;
ws1.Cell(3, 2).Value = cellName;
ws1.Cell(4, 2).Value = ReportDate;
int amntIncr = 0;
while (AmountList.Count > amntIncr)
{
ws1.Cell(PeriodColIndex, PeriodRowIndex).Value = "Period";
ws1.Cell(Desc1ColIndex, Desc1RowIndex + 2).Value = AmountList[amntIncr];
ws1.Cell(Desc2ColIndex, Desc2RowIndex + 2).Value = (AmountList[amntIncr + 1]);
ws1.Cell(Desc3ColIndex, Desc3RowIndex + 2).Value = (AmountList[amntIncr + 2]);
PeriodRowIndex++;
Desc1RowIndex++;
Desc2RowIndex++;
Desc3RowIndex++;
amntIncr = amntIncr + 3;
}
int periodDateIncr = 0;
while (PeriodDateList.Count > periodDateIncr)
{
ws1.Cell(PeriodDateColIndex, PeriodDateRowIndex).Value = PeriodDateList[periodDateIncr];
PeriodDateRowIndex++;
periodDateIncr = periodDateIncr + 3;
}
var ws2 = workbook.Worksheet(2);
ws2.Cell(1, 2).Value = DomicileName;
ws2.Cell(2, 2).Value = CapitiveName;
ws2.Cell(3, 2).Value = cellName;
ws2.Cell(4, 2).Value = ReportDate;
SqlParameter paramCellId = new SqlParameter("#CellId", CellId);
SqlParameter paramReportDate = new SqlParameter("#ReportDate", ReportDate);
DataTable dt = new DataTable();
var data = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "Usp_inputResult", paramCellId, paramReportDate).Tables[0];
List<string> lstClmwiseData = new List<string>();
foreach (DataRow r in data.Rows)
{
foreach (DataColumn c in data.Columns)
{
lstClmwiseData.Add(r[c].ToString());
}
}
int snoColIndex = 6, GLCodeColIndex = 6, DescriptioColIndex = 6, movementDebitColIndex = 6, movementCreditColIndex = 6, ClosingdebitcolIndex = 6, ClosingCreditColIndex = 6;
int snoRowIndex = 1, GLCodRowIndex = 2, DescriptioRowIndex = 3, movementDebitRowIndex = 4, movementCreditRowIndex = 5, ClosingdebitRowIndex = 6, ClosingCreditRowIndex = 7;
int secondSheet = 0;
int SnoIncrement = 1;
while (lstClmwiseData.Count > secondSheet)
{
ws2.Cell(snoColIndex, snoRowIndex).Value = SnoIncrement;
ws2.Cell(GLCodeColIndex, GLCodRowIndex).Value = lstClmwiseData[secondSheet];
ws2.Cell(DescriptioColIndex, DescriptioRowIndex).Value = lstClmwiseData[secondSheet + 1];
ws2.Cell(movementDebitColIndex, movementDebitRowIndex).Value = lstClmwiseData[secondSheet + 2];
ws2.Cell(movementCreditColIndex, movementCreditRowIndex).Value = lstClmwiseData[secondSheet + 3];
ws2.Cell(ClosingdebitcolIndex, ClosingdebitRowIndex).Value = lstClmwiseData[secondSheet + 4];
ws2.Cell(ClosingCreditColIndex, ClosingCreditRowIndex).Value = lstClmwiseData[secondSheet + 5];
snoColIndex++;
GLCodeColIndex++;
DescriptioColIndex++;
movementDebitColIndex++;
movementCreditColIndex++;
ClosingdebitcolIndex++;
ClosingCreditColIndex++;
SnoIncrement++;
secondSheet = secondSheet + 6;
}
string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + #"\Downloads\ReportUtitlity";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string FileName = workbook.Author + "_" + "Report_"+CellId+ "CellId" +"_" + $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}";
workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + #"\Downloads\ReportUtitlity\" + FileName + ".xlsx");
}

XML Parsing Error: no element found Location When I use Interop.Excel For generate an Excel

I use Interop.Excel library to generate an Excel file,but when I send My request I see this error
XML Parsing Error: no element found Location: moz-nullprincipal:{0acbe7aa-8d90-47b2-8a34-2ce0a4ee6557} Line Number 1, Column 1:
also I set Full Control permissions for my folder to Everyone.I see this error when i publish my project to server but in local system i do not see any error
This is my code:
public class GenerateExcel
{
System.Data.DataTable dtCustmer = new System.Data.DataTable();
object[] query;
public void CreateExcel<T>(T[] listObj, string fileName, string sheetName = "sheet")
{
string generatefileName = fileName + HttpContext.Current.Request.Cookies["ImenBourse"]["userId"];
dtCustmer = ConvertToDatatable(listObj);
string newFilePath = HttpContext.Current.Server.MapPath(generatefileName + ".xlsx");
Excel._Application objExcel = new Excel.Application();
Workbooks objBooks = null;
_Workbook objBook = null;
Sheets objSheets = null;
_Worksheet objSheet = null;
Range objRange = null;
int row = 1, col = 1;
try
{
objBooks = (Workbooks) objExcel.Workbooks;
objBook = objBooks.Add(XlWBATemplate.xlWBATWorksheet);
int j = col;
foreach (DataColumn column in dtCustmer.Columns)
{
objSheets = (Sheets) objBook.Worksheets;
objSheet = (_Worksheet) objSheets.get_Item(1);
objRange = (Range) objSheet.Cells[row, j];
objRange.Value2 = column.Caption;
j++;
}
row++;
int count = dtCustmer.Columns.Count;
foreach (DataRow dataRow in dtCustmer.Rows)
{
int k = col;
for (int i = 0; i < count; i++)
{
objRange = (Range) objSheet.Cells[row, k];
objRange.Value2 = dataRow[i].ToString();
k++;
}
row++;
}
objSheet.Name = sheetName;
object objOpt = Missing.Value;
Excel.Application excelApp =
(Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
excelApp.Visible = true;
string workbookPath="";
//if (!File.Exists(newFilePath))
//{
//objBook.SaveAs(newFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault,
// Type.Missing,
// Type.Missing,
// false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
// Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbookPath = newFilePath;
//}
excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
objBook.Close();
}
catch
{
//return null;
}
finally
{
objExcel = null;
objBooks = null;
objBook = null;
objSheets = null;
objSheet = null;
objRange = null;
ReleaseComObject(objExcel);
ReleaseComObject(objBooks);
ReleaseComObject(objBook);
ReleaseComObject(objSheets);
ReleaseComObject(objSheet);
ReleaseComObject(objRange);
}
}
public void ReleaseComObject(object reference)
{
try
{
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(reference) <= 0)
{
}
}
catch
{
}
}
public static DataTable ConvertToDatatable<T>(T[] list)
{
PropertyInfo[] properties = list.GetType().GetElementType().GetProperties();
DataTable dt = CreateDataTable(properties);
if (list.Length != 0)
{
foreach (object o in list)
FillData(properties, dt, o);
}
return dt;
}
private static DataTable CreateDataTable(PropertyInfo[] properties)
{
DataTable dt = new DataTable();
DataColumn dc = null;
foreach (PropertyInfo pi in properties)
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayNameAttribute));
dt.Columns.Add(attr.DisplayName, pi.PropertyType);
}
return dt;
}
private static void FillData(PropertyInfo[] properties, DataTable dt, Object o)
{
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in properties)
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayNameAttribute));
if (dt.Columns.Contains(attr.DisplayName))
{
dr[attr.DisplayName] = pi.GetValue(o, null);
}
}
dt.Rows.Add(dr);
}
}

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

Categories