Export to Excel - preventing phone numbers from scientific notation in C# - 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.

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,

C# doesn't recognize some symbols

I read strings from text file, and among the strings there is one: "15121 ♥☺020 000000/=n531☻".
I use .Contain() method to spot ♥☺☻ symbols in the string, but it doesn't recognize them. For ♥,☺,☻ I also tried \u2665, \u263a, \u263b (as arguments for .Contain()), but none of them were recognized.
Moreover, I copied the string (from console output window) and pasted it into my code to compare symbols one by one.
string s = "15121 ♥☺020 000000/=n531☻"; // the same with "15121 \u2665\u263a020 000000/=n531\u263b"
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
This is what I got:
What may be wrong and how do I recognize those symbols?
UPDATE: The input file I read strings from is a usual text file, and the strings inside looks like these (txt opened in Notepad):
As you can see, there is THE string among the others.
I don't use any encoding when reading the txt, and to specify how I do read the file and what the line is, here is my code:
string[] lines = File.ReadAllLines(path + target_file_name);
var list = new List<string>(lines);
for (int i = 0; i < list.Count; i++)
{
string line = list[i];
if (line.Length > 21)
{
Console.WriteLine(line);
if (line.Contains("/=n")) //used just to catch THE string
{
var line_b = Encoding.Unicode.GetBytes(line);
Console.WriteLine($"{line_b} : line = {line}");
foreach (byte m in line_b)
{
Console.Write(m + " ");
}
string s = "AAXX 15121 ♥☺020 000000/=n531☻";
Console.WriteLine();
var s_b = Encoding.Unicode.GetBytes(s);
Console.WriteLine($"{s_b} : s = {s}");
foreach (byte n in s_b)
{
Console.Write(n + " ");
}
Console.WriteLine();
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
}
Reading all the lines from txt and converting them to List is a must for me. Thus, the line is a string line from initial txt file.
I have dumped the bytes of the inout text string var b = Encoding.Unicode.GetBytes(line); and compare with my literal (#pm100), and here is the result. Not quite sure what it does give me:
I'm sorry, I'm not willing to publish my code, and I may not understand some of your suggestions for I'm not very proficient in C# (and coding in general). So I would appreciate any further help as it is, if possible.

convert jquery chat to csv using asp.net

I need to convert jquery chart into csv file.
can you please help me with the function.
I all ready have the graphs but i could not find the function to convert my graph into csv and download it.
Actually i found this option right here :
http://flotr.googlecode.com/svn/trunk/flotr/examples/prototype/data-download.html
but there is no code for that.
Thanks
Just looked in the source of the page and got you the function that is doing the magic there. May it helps you -
/**
* Converts the data into CSV in order to download a file
*/
downloadCSV: function(){
var i, csv = '',
series = this.series,
options = this.options,
dg = this.loadDataGrid(),
separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")";
}
// The first row
for (i = 0; i < series.length; ++i) {
csv += separator+'"'+(series[i].label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"';
}
csv += "%0D%0A"; // \r\n
// For each row
for (i = 0; i < dg.length; ++i) {
var rowLabel = '';
// The first column
if (options.xaxis.ticks) {
var tick = options.xaxis.ticks.find(function(x){return x[0] == dg[i][0]});
if (tick) rowLabel = tick[1];
}
else if (options.spreadsheet.tickFormatter){
rowLabel = options.spreadsheet.tickFormatter(dg[i][0]);
}
else {
rowLabel = options.xaxis.tickFormatter(dg[i][0]);
}
rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"';
var numbers = dg[i].slice(1).join(separator);
if (options.spreadsheet.decimalSeparator !== '.') {
numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
}
csv += rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n
}
if (Prototype.Browser.IE && !Flotr.isIE9) {
csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
window.open().document.write(csv);
}
else window.open('data:text/csv,'+csv);
}
});
If you have problems with this code here's a link to the whole source - Flotr
You could also get the Table with the class "flotr-datagrid" and convert it in JavaScript (HowTo) or send it via PostBack to your asp server and do the magic serverside via C#.

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

Creating a binary file from an IntelHex in C#

I'm trying to create a binary file from a intelHex file. Iside the intelHex file I have data and address to which I should write the data inside the binary file.
IntelHex file looks like that
:10010000214601360121470136007EFE09D2190140
:100110002146017EB7C20001FF5F16002148011988
:10012000194E79234623965778239EDA3F01B2CAA7
:100130003F0156702B5E712B722B732146013421C7
:00000001FF
So I have 4 lines here with data since the last one tells us thats the end of file.
Here is what I'm doing to create the file
while (!streamReader.EndOfStream)
{
string temp = String.Empty;
int address = 0;
line = streamReader.ReadLine();
// Get address for each data
address = Convert.ToInt32(line.Substring(3, 4), 16);
// Get data from each line
temp = line.Substring(7, 2);
if (temp == "01")
break;
else
{
temp = line.Substring(9, line.Length - 11);
string[] array = new string[(temp.Length / 2)];
int j = 0;
for (int i = 0; i < array.Length; ++i)
{
array[i] = temp[j].ToString() + temp[j + 1].ToString();
j = j + 2;
}
temp = String.Empty;
for (int i = 0; i < array.Length; ++i)
{
temp = temp + Convert.ToChar(Convert.ToInt32(array[i], 16));
}
}
binaryWriter.Seek(address, SeekOrigin.Begin);
binaryWriter.Write(temp);
binaryWriter.Flush();
}
Console.WriteLine("Done...\nPress any key to exit...");
The problem here is, that data in binary file in some places is not equal to data from the intelHex file. Looks like there is some random data added to the file and I do not know from where. First time I saw that there is an additional data before the data from the intelHex file. For instance first data line starts with 21, but in binary file I have a number 12 before the 21. I do not know what is wrong here. Hope someone can help me or guide me where I can find some usefull informations about creating binary files in C#
<Generic answer pointing out that a Unicode character (char) is not an octet (byte), and that the code produces the wrong output because binary data is written as Unicode string to the file.>
Hint: use a byte[] for binary data, not a string.
Also: In before answers suggesting to use a StringBuilder for the loop.

Categories

Resources