How to insert rich text to excel file from c# - c#

I have a requirement of inserting bold and underlined text to excel file while preserving new line through c# code in windows form application. My function is as below:
private bool insertIntoExcel(string pathname , string sheetname ,int excelRow, int excelColumn,string value)
{
try
{
Microsoft.Office.Interop.Excel._Application oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook mWorkBook = oXL.Workbooks.Open(pathname, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
Microsoft.Office.Interop.Excel._Worksheet mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item(sheetname);
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
mWSheet1.Cells[excelRow, excelColumn] = value;
}catch
{
return false;
}
return true;
}
this code dosen't preserves new linw, bold, underline and bullets line. How to achieve this? Thanks

if your value has '\n' or Environment.NewLine maybe you can split it by these characters:
For example:
string[] newLineChars = { "\n", Environment.NewLine};
string[] splittedVals = value.Split(newLineChars, StringSplitOptions.None);
foreach (string val in splittedVals)
{
mWSheet1.Cells[excelRow, excelColumn] += val;
}

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!

How to read cell values that are dynamically generated using macros in c#?

I have an excel file in which some cell values are generating dynamically using macro.
File is also read-only.
I have to read these dynamically generated values using c# code.
Use following macro code to generate cell values:
**Sub abc()
Range("E5").Value = "string"
Range("E6").Value = 2
End Sub**
Thank You...!
Check if you need to connect to already opened excel file.
If you use excelApp.Workbooks.Open, it is not reflecting sheet data updated by macros.
Instead, try BindToMoniker method as follows:
private void btnGetXLSValue_Click(object sender, EventArgs e)
{
object _row = 5;
object _column = 5;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook ;//= excelApp.Workbooks.Open(#"C:\July.xlsm", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get a reference to the Workbook object by using a file moniker.
//The xls was saved earlier with this file name.
excelWorkbook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(#"C:\July.xlsm");
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "July 2015";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.UsedRange;
string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).get_Value(range).ToString();
MessageBox.Show(sValue);
}

How to check if a cell is empty (Excel\VisualC#)

My aim is to check line per line in the Sheet1 in order to discover how many rows are, so i put a do\while that should stop once it reaches a blank cell
Example:
row1 data row2 data row3 datarow4 datarow5 data
row6 data row7 data
In this case I need only the first 5 rows, so the do\while check is intended to stop once it reaches the blank cell. This doesn't happens, because the check doesn't loop (it stops after completing a circle like it finds a blank cell even if it is filled with data).
string str;
int rCnt = 11; //the data I need is after the 10th row in excel
int cCnt = 1;
int valori = 1;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(label4.Text, 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows,
"", true, false, 0, true, false,
false);
Excel.Sheets xlsheet = xlWorkbook.Worksheets;
string sheet1 = "Sheet1";
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlsheet.get_Item(sheet1);
Excel.Range xlCell;
do
{
rCnt++;
str = "A" + rCnt;
xlCell = (Excel.Range)xlWorksheet.get_Range(str, str);
} while (xlCell.Value2 == null);
I tried changing Value2 to Value or Text and trying to set == "" instead of null.
If you want the loop stop when reach blank cell then .. Try to change
while (xlCell.Value2 == null);
with
while (! IsNull(xlCell.Value2));
Simple way to check a cell is empty:
if (sheet.Cells[4,3] == null || sheet.Cells[4,3].Value2 == null || sheet.Cells[4,3].Value2.ToString() == "")
MessageBox.Show(“cell on row 4 col 3 is empty”);
You can use the Text property of the selected cell. It can be converted to a string type via "as". The result string can already be checked as usual in C#, like not-empty
string TempText = excelWorksheet.Cells[1, 1].Text as string;
if (!string.IsNullOrWhiteSpace(TempText)){
// actions
}
The issue mainly comes from when you don't know what sort of data to expect. When I work with Excel reads I often do something similar to:
var _cell = range.Cells[1, 2].Value2;
if (_cell.GetType() != typeof(Double))
In your instance if you always are getting a string returned then you should be able to assume the cast:
string _str = (string)(range.Cells[str, str] as Excel.Range).Value2;
and then check that is not empty.
This is working for me:
using Excel = Microsoft.Office.Interop.Excel; to read excelsheet:
var excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[2];
Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
string wwdEmpty = Convert.ToString(excelRange.Cells[5, 14].value2);
// this is working code with NULL Excell cell
do
{
rCnt++;
str = Sheet.Cells[rCnt, 5].Value;
} while (str != null);

Format Excel File using C#

The Bellow function is used to formate the excel file but after running the function the Application Excel is not closeing from the Try.. (not able to kill the application) Please Help me on this
private void FormateExcelFile()
{
try
{
int nI = 0;//For Loop
string nFieldName = string.Empty;
nUserName= WindowsIdentity.GetCurrent().Name; //Get Windows Login User
string reportFilenPath = Application.StartupPath + "\\OutPutFiles\\" + "NewTempFile.xls";
string connString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + reportFilenPath + "';Extended Properties=Excel 8.0;";
DataTable parts = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connString))
{
string sqlParts = "Select * from [" + nSheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(sqlParts, conn);
adapter.Fill(parts);
}
for (nI = 0; nI < parts.Columns.Count; nI++)
{
DataColumn column = parts.Columns[nI];
if (nI == 0) { nFieldName = column.ColumnName; }
else { nFieldName = nFieldName + "," + column.ColumnName; }
}
parts.Dispose(); parts = null;
oExcel = new Excel.Application();
oBook = oExcel.Workbooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets.get_Item(nSheetName.Replace("$", ""));
oExcel.DisplayAlerts = false;
oExcel.Visible = true;
//Check the Field Is Avilable in the Sheet if not then Add
if (nFieldName.Contains("Sub Device") == false)
{
nRng = oSheet.get_Range("A1", oMissing);
nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
oSheet.Cells[1, 1] = "Sub Device";
}
if (nFieldName.Contains("Brand") == false)
{
nRng = oSheet.get_Range("A1", oMissing);
nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
oSheet.Cells[1, 1] = "Brand";
}
if (nFieldName.Contains("Model") == false)
{
nRng = oSheet.get_Range("A1", oMissing);
nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
oSheet.Cells[1, 1] = "Model";
}
if (nFieldName.Contains("Product Details") == false)
{
nRng = oSheet.get_Range("A1", oMissing);
nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
oSheet.Cells[1, 1] = "Product Details";
}
if (nFieldName.Contains("Price") == false)
{
nRng = (Excel.Range)oSheet.Cells[1, 1];
//nRng = oSheet.get_Range("A1", oMissing);
nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
oSheet.Cells[1, 1] = "Price";
}
oBook.Save();
oBook.Close(false, oMissing, oMissing);
oExcel.DisplayAlerts = true;
releaseObject(oSheet);
releaseObject(oBook);
oExcel.Quit();
releaseObject(oExcel);
releaseObject(nRng);
nRng = null;
oExcel = null;
oSheet = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
releaseObject(oSheet);
releaseObject(oBook);
//oExcel.Quit();
releaseObject(oExcel);
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
You need to release all the Excel objects you're referencing. For example:
if (nFieldName.Contains("Sub Device") == false)
{
nRng = oSheet.get_Range("A1", oMissing);
nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
oSheet.Cells[1, 1] = "Sub Device";
}
should be something like (leaving out try/finally for simplicity)
if (nFieldName.Contains("Sub Device") == false)
{
nRng = oSheet.get_Range("A1", oMissing);
var col = nRng.EntireColumn
col.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
var cells = oSheet.Cells;
var firstCell = cells[1,1];
firstCell.Value = "Sub Device";
Marshal.ReleaseComObject(nRng);
Marshal.ReleaseComObject(col);
Marshal.ReleaseComObject(cells);
Marshal.ReleaseComObject(firstCell);
}
Similarly:
oBook = oExcel.Workbooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets.get_Item(nSheetName.Replace("$", ""));
needs to be:
oBooks = oExcel.Workbooks
oBook = oBooks.Open(...);
oSheets = oBook.Worksheets
oSheet = oSHeets.get_Item(...);
and you need to release oBooks and oSheets.
Try to end your excel task with these commands:
Marshal.FinalReleaseComObject(sheet);
app.DisplayAlerts = false; //Very important!
range = null;
sheet = null;
// Garbage collecting
GC.Collect();
GC.WaitForPendingFinalizers();
book.Close(false, Missing.Value, Missing.Value);
Marshal.FinalReleaseComObject(book);
book = null;
app.Quit();
Marshal.FinalReleaseComObject(app);
app = null;
I had the same problem accessing my excel files, but with the shown code it closes all the time.
Of course not if the program crashes before it reaches the code, check your code with the debugger.
In your case: book --> oBook, app --> oExcel, sheet --> oSheet.
Take away these lines:
nRng = null;
oExcel = null;
oSheet = null;
I think you are releasing your Excel object, and then by making it equal to null afterwards you are doing something with Excel which starts a new instance on your machine.
After releasing the object, you don't need to set variables to null, or run GC.Collect();, the garbage collector will take care of this for you, and I think in this instance trying to clean up the managed objects yourself (after correctly cleaning up the unmanaged Excel object) is actually causing your problems.
I had the same kind of issue working with Excel interop. The problem should be originated by this kind of lines (at least it was in my case):
oBook = oExcel.Workbooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
In the end you reales oBook, but this is what's really happening here: in order to get oBook pointing to your opened workbook, you accessed a Workbooks object (using oExcel.Workbooks). This is never released, and keeps Excel from quitting.
I solved the problem by rewriting that line as:
Microsoft.Interop.Excel.Workbooks oBooks = oExcel.Workbooks;
oBook = oBooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
releaseObject(oBooks);
Of course this has to be done for every line of this kind (for instance oBook.Worksheets.get_Item(...), nRng.EntireColumn.Insert(...), and so on).

"Exception from HRESULT: 0x800A01A8"

I've written this code to count the number of rows that are populated in an excel worksheet. It works until it gets yo a certain number of rows (not the total). Then comes up with the error message "Exception from HRESULT: 0x800A01A8" Any help much appreciated
namespace ConsoleApplication1
{
class ExcelClass
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Excel.Application excelApp = new Excel.Application(); // Creates a new Excel Application
excelApp.Visible = true; // Makes Excel visible to the user.
// The following code opens an existing workbook
string workbookPath = "D:\\RSG_D.xls"; // Add your own path here
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
// The following gets the Worksheets collection
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
// The following gets Sheet1 for editing
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
//void SetNewCurrentCulture()
//{
oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//}
int rowCounter = 1;
while ( rowCounter != null)
{
Excel.Range countRows = (Excel.Range)excelWorksheet.Cells[rowCounter, 1] as Excel.Range;
object CountRows = countRows.Value;
rowCounter++;
Console.WriteLine(CountRows);
}
excelWorkbook.Close(0);
excelApp.Quit();
//reset Current Culture back to the originale
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}
}
}
I had the exact same problem tonight: Here is the code I have used and it's worked properly for me:
Excel.Application oExcel = new Excel.Application();
//oExcel.Visible = true; (this caused me huge problems
Excel.Workbook oBook = oExcel.Workbooks.Open(#"C:\Yoink\Birr Castle Demesne Interactive Map\Birr Castle Demesne Interactive Map\bin\Debug\Red Tree Trail.xlsx");
Excel.Worksheet oSheet1 = oBook.Worksheets["Red Tree Trail"] as Excel.Worksheet; (use your own worksheet title there)
Excel.Range rng = oSheet1.get_Range("A1", "AJ51"); (use your own range there
int rowCount = rng.Rows.Count;
int colCount = rng.Columns.Count;
string[,] tsReqs = new string[rowCount, colCount];
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
string str = rng.Cells[i, j].Text;
tsReqs[i - 1, j - 1] = str;
}
}
I think your problem is in this line:
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);

Categories