Import Rich Text Data From Excel Sheet Using c# - c#

I want to import data from excel sheet with richtext i.e. font family
But I can get only bold and italic style using below given code
Microsoft.Office.Interop.Excel.Range Range = (Microsoft.Office.Interop.Excel.Range)Cell;
int TextLength = Range.Text.ToString().Length;
for (int CharCount = 1; CharCount <= TextLength; CharCount++)
{
Microsoft.Office.Interop.Excel.Characters charToTest = Range.get_Characters(CharCount, 1);
bool IsBold = (bool)charToTest.Font.Bold;
bool IsItalic = (bool)charToTest.Font.Italic;
// other formatting tests here
}
Can anybody help me to get the rich text data from Excel Sheet using Interop or any other method in c#.net
Thanks in advance

How about:
Range someRange = activeWorksheet.Range["A1", "A1"];
var fontFamily = someRange.Font.Name;

Related

Writing into word document with different font sizes, etc

I am trying to pick string values from different Excel worksheets and write it into Word. However, each text line will have different font size, bold and underline.
I managed to pull all values into Word with StringBuilder, however I am not able to format each line way I wanted, therefore trying to make other solution without StringBuilder.
Please see code below. Unfortunately, the end result has only the last row of Excel sheet value.
Anyone has idea, what I can do here:
for (int c = 0; c < aList.Count; c++)
{
Worksheet excelWorksheet = excelWorkbook.Worksheets[aList[c]];
Microsoft.Office.Interop.Excel.Range lastRow = excelWorksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell);
int lastUsedRow = lastRow.Row;
currentItemNumber = "Item " + (c + 1).ToString();
docRange.Text = currentItemNumber;
docRange.Font.Bold = 1;
docRange.Font.Size = 12;
docRange.Font.Underline = (WdUnderline)1;
docWholeRange.Text = docRange.Text;
for (int d = 0; d < lastUsedRow; d++)
{
if (d == 0)
{
currentRowValue = excelWorksheet.Range["A" + (d + 1)].Value2 + "\t" + excelWorksheet.Range["D"+(d+1)].Value2;
docRange.Text = currentRowValue;
docRange.Font.Bold = 0;
docRange.Font.Size = 12;
docRange.Font.Underline = (WdUnderline)0;
docWholeRange.Text = docWholeRange.Text + docRange.Text;
}
else
{
currentRowValue = excelWorksheet.Range["A" + (d + 1)].Value2+ excelWorksheet.Range["B" + (d + 1)].Value2+ excelWorksheet.Range["C" + (d + 1)].Value2;
docRange.Text = currentRowValue;
docRange.Font.Bold = 0;
docRange.Font.Size = 10;
docRange.Font.Underline = (WdUnderline)0;
docWholeRange.Text = docWholeRange.Text + docRange.Text;
}
}
wordDocument.Bookmarks.Add(bookmarkPlace, docWholeRange);
}
I tried using StringBuilder, however it is not possible to format each line separately and keep it formatted.
Then tried using Selection object in similar manner as shown in code and then tried to use Selection.TypeText. Instead of being entered at Bookmark place, it was actually starting from the beginning of word file. The size of the letter was way too small.
Managed to get all lines correctly to be written in Word without using StringBuilder.
However, trying to get all text lines between two bookmarks and all samples advising to use Bookmarks.get_Item and this does not exists in Visual Studio 2019 and C#.
Anyone has idea, how to store it into Range?
Tried following:
object start = bm.Range.End;
object end = ebm.Range.Start;
Microsoft.Office.Interop.Word.Range textRange = wordDocument.Range(ref start, ref end);
bm and ebm are two bookmarks.
I am trying to store all text line into range, then iterate line by line and change font size/bold in each text line.
Anyone has better idea how it can be done.
Regards,

Export to Excel - preventing phone numbers from scientific notation in C#

I am exporting data from the DB to excel in C# and it has a phone number column eg +22200073886. How do I Export to excel without converting the number to scientific notation?
var csv = new StringBuilder();
string strContent = "";
int counter = DS.Tables[0].Columns.Count;
// Build the file content
for (int i = 0; i <= DS.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < counter; j++)
{
if (i == 0)
{
strContent += DS.Tables[0].Columns[j].ToString() + ",";
}
else
{
strContent += DS.Tables[0].Rows[i - 1][j].ToString() + ",";
}
}
csv.AppendLine(strContent.Substring(0, strContent.Length - 1));
strContent = "";
}
File.WriteAllText(new Page().Server.MapPath(filePath), csv.ToString());
First you must not to save a CSV file with XLS extension. You must export real Excel file, like xls or xlsx, using OpenXML or any other library for Excel that can be used from C#.
Then, you must save your data in cell as string or set the number format of the cell as text. The number format for text is "#". The code depends on the solution you choose.

Excel Open xml sdk - Copy formula between cells with range modification

I have a cell with formula (CellFormula). I don't know the formula content (Might be Sum, ifs or any other calculation).
The formula might include range.
When you drag the cell to other cells (manually at excel application itself) the formula range get updated.
I want the formula programatic copy to behave the same way.
If the formula contains range specifiers I want to update them to the current row.
Is there some built-in way to do so without regular expression manipulations?
I don't know if it's a good solution that cover all possibilities but...
//Formula update
if (cloneFromCell.CellFormula != null && (cloneFromCell.CellFormula.FormulaType == null || !cloneFromCell.CellFormula.FormulaType.HasValue || cloneFromCell.CellFormula.FormulaType.Value == CellFormulaValues.Normal))
{
uint cloneRowIndex = OXMLTools.GetRowIndex(cloneFromCell.CellReference);
uint offset = rowIndex - cloneRowIndex;
exCell.CellFormula.Text = OXMLTools.GetUpdatedFormulaToNewRow(cloneFromCell.CellFormula.Text, offset);
}
public static string GetUpdatedFormulaToNewRow(string formula, uint offset)
{
return Regex.Replace(formula, #"[A-Za-z]+\d+", delegate(Match match)
{
//Calculate the new row for this cell in the formula by the given offset
uint oldRow = GetRowIndex(match.Value);
string col = GetColumnName(match.Value);
uint newRow = oldRow + offset;
//Create the new reference for this cell
string newRef = col + newRow;
return newRef;
});
}

how to add a red string to a word 2010 addin in C#

I'm kinda new to building word add-ins with C# and I have a question that regards strings and font colors. I want to add a red string to an existing string in a cell on word 2010,
something like this:
Word.Range r = document.Range(0, 0);
r.Text = "text";
r.Font.ColorIndex = WdColorIndex.wdRed;
tbl.Cell(RowNum, RightColumn).Range.Text += r;
Any ideas?
Well, I figured something out, I did this:
int TblRng = tbl.Cell(RowNum, RightColumn).Range.End;
Range r = document.Range(TblRng-1, TblRng+1);
r.Text = Final;
r.Font.ColorIndex = WdColorIndex.wdRed;
int TblRng = tbl.Cell(RowNum, RightColumn).Range.End; - this defined the new range at the end of the location where I needed to add the red string.
If you want to replace an existing string with new red then use bellow code
object findText = stringText;
if (Range.Find.Execute(ref findText))
{
Range.Text = NewString; // replace old string with New
Range.Font.Color = WdColor.wdColorRed; // Set color of the string
}

Convert Excel Cell Value From Text To Number Using C#

I am using Windows Application. In that Application i exported the DataGrid into Excel Successfully... Now the problem is , When i exported from Grid to the Excel Sheet, The cell values are having some green color mark on left top corner in the Excel Sheet... I thought that is type cast problem . How Shall i avoid that Problem.... and How to change the cell value from text to Number ...(i.e)Convert To Number....
Can Anyone tell me the solution of this problem?
My Code for Formatting That Excel Sheet For Some Range of Values,
wksheet.Range[GetRanges[0].ToString(), GetRanges[GetRanges.Count-2].ToString()].Merge();
wksheet.get_Range(GetRanges[0].ToString(), GetRanges[GetRanges.Count-].ToString()).Interior.Color = Color.FromArgb(192, 0, 0);
I haven't a Windows machine to test on at the moment, but perhaps you would want to try changing the cell format, e.g.:
my_range.NumberFormat = "0.0"; // change number of decimal places as needed
Here's a full example from Microsoft: How to automate Microsoft Excel from Microsoft Visual C#.NET.
The following routine will dynamically fill a spreadsheet from data (text and numbers) in a text file.
The kicker is using an object array to set the values.
StreamReader STRead;
String[] STCells;
object[] cellData;
int temp;
Excel.Range tempRange;
for (int i = 0; i < FileList.Length; i++)
{
STRead = FileList[i].OpenText();
int j = 0;
while (!STRead.EndOfStream)
{
STCells = STRead.ReadLine().Split(',');
cellData = new object[STCells.Length];
for (int k = 0; k < STCells.Length; k++)
{
if (Int32.TryParse(STCells[k], out temp))
cellData[k] = temp;
else
cellData[k] = STCells[k];
}
tempRange = sheetList[i].get_Range(ReturnCellID(j, 0),
ReturnCellID(j, STCells.Length - 1));
j++;
tempRange.Value2 = cellData;
}
STRead.Close();
}
I had this problem with a excel sheet containing both regular numbers and percent (a result of an export of strings from a Crystal Report).
To change all of them at once I made a loop somewhat like this:
//example range
Excel.Range rng = mWorkSheet.get_Range("A1", "H25");
foreach (Excel.Range range in rng)
{
if (range.Value != null)
{
int number;
bool isNumber = int.TryParse(range.Value.ToString().Trim(), out number);
if (isNumber)
{
range.NumberFormat = "#,##0";
range.Value = number;
}
else
{
//the percent values were decimals with commas in the string
string temp = range.Value.ToString();
temp = temp.Replace(",", ".");
range.Value = temp;
}
}
}
Result was that both the percentage strings and the numbers got converted into the correct Excel format.
When you assign the value to the cells, try to get all the values in an 2 dimensional array first and then assign the array to the Range. this way its going to be very fast and also i guess the values in the cell will be number. try it out ...hopefully it should work
Change the cell value from text to Number is easy with Excel Jet Cell .NET component.
Cell["A1"].Style.StringFormat = "##.#"; // or "0.0" same as in MS Excel

Categories

Resources