how to change the formatting of chart legends - c#

I want to set a number format of the lengends on a chart with the next format:
300.000 kWh
Actually i get 300000.
How can i do this.
I tried do it manually with Excel setting the format of the cell to personalized number format in the dialog cell Format adding this format # "kWh".
With this trick, I can do. But I need to do this when I generate the excel, and not when the excel is generated...

cells["kwhcell"].Style.NumberFormat = "#.##0,00 kWh";

You can't directly. You'll have to loop all the cells and do the formatting yourself.
for (int i = 1; i <= excelWorksheet.Dimension.End.Row; i++)
{
string cellValue = string.Format("{0:N2}", Convert.ToDecimal(excelWorksheet.Cells[i, 1].Value)) + " kWh";
excelWorksheet.Cells[i, 1].Value = cellValue;
}

I sloved my Problem.
This is the correct code to answer my question
wsData.Cells[2, (z + 1)].Style.Numberformat.Format = "#0,0 \"kwh\"";
and
wsData.Cells[2, (z + 1)].Style.Numberformat.Format = "#0,0 \"ÂșC\"";

Related

Excel does not work the sum in the status bar for a file generated in C#

In Excel does not work the sum in the status bar for a file generated in C#. In the code I set the cell format as a number. Any idea what might be going on?
My code:
oWorksheet.Cells[vLinhaCelula, 7].NumberFormat = "0";
oWorksheet.Cells[vLinhaCelula, 7].Value = vValorNF.Replace(".", "");
oWorksheet.Cells[vLinhaCelula, 7].HorizontalAlignment = XlHAlign.xlHAlignRight;
Thanks for any help.
My guess is that vValorNF.Replace(".", ""); is returning a string, and therefore the cell becomes a string regardless of the number formatting. Try specifically creating a double or decimal
double num = Double.Parse(vValorNF.Replace(".", ""));
and then assigning
oWorksheet.Cells[vLinhaCelula, 7].Value = num;

C# : Error Printing the Date Value in Excel

I am building a winform based Desktop application. As part of the application, I am generating the Excel output.
I am getting a error, when I am trying to enter the date value.
In C#, the date value is "11-10-12". However, in Excel, it is printing as 10-11-2012.
Here is the code, which does it :
String Date1 = "11-10-12";
oSheet.Cells[i + 2, 1] = DateTime.ParseExact(Date1, "dd-MM-yy", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy");
Any idea what could could be wrong ?
EDIT
The Cell format in Excel was by default General. However, when the values are entered, it is changed to Date.
Try changing the format of the excel-Cell with:
yourCellRange.NumberFormat = "dd-MM-yy";
or adjust the string format to the excel-format.
Try doing this
worksheet.get_Range(Cell1, Cell2 + worksheet.Rows.Count).NumberFormat = "dd-mmm-yyyy";
When you are adding the value you can try
worksheet.Cells[row, column] = String.Format("{0:dd-MMM-yyyy}", Date1);
None of the suggestion helped unfortunately. So, I disabled the automatic formatting in Excel :
So, here is the code snippet which disables the automatic (Date) formatting in Excel :
String Date1 = "11-10-12";
oSheet.Cells[i + 2, 1] = "'" + Date1;
So, the trick is to preceed the String with an apostrophe which worked.
Thanks
Try just:
DateTime.Now.ToString("dd-MM-yy");
or:
String Date1 = "11-10-12";
var Format = "dd-MM-yy";
var TimeBuff = DateTime.ParseExact(Date1, Format,
CultureInfo.InvariantCulture).ToString(Format);
oSheet.Cells[i + 2, 1] = TimeBuff;
Both Parse and ToString must contains the same Format. If you get the same its definitely a Excel failure.
Edit:
Just for DJ KRAZE

How can i change the text format of a Excel Cell using C#?

I am currently writing an application (C#) to generate reports in a excel file, based on other reports.
The problem is that, once get an number from a certain sheet, and copy to another one, the destination cell is not formated correctly, and the number does no display correctly.
E.g :
Number from source : 14.34
Number on destination : 14.345661
How do i format the destination cell to force the number formating to be the same as the source cell.
Thanks !
The format of a given cell/range in excel can be set via code.
public void SetCustomFormat(string format, int r, int c)
{
((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;
}
In your specific case, I believe you would need to use the format "#.00" or "#.##"
Here's a snippet from some code I've got in use, to show you the general pattern for formatting cells. Obviously, there are some variables declared, but it should show you what you need.
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Font.Bold = true;
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Interior.Color = Color.Silver.ToArgb();
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
sheet.get_Range("A" + CompetencyStartRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
That first line, assuming CurrentRowIndex = 1 and ColPrefix = "B", replacing the variables with the resulting values would translate into
sheet.get_Range("A1", "B1").Font.Bold = true;
At any rate, you want to set the numberformat. (Coming..)
sheet.Cells[Row, Column].NumberFormat = "0.00"

How to convert Text values to number values in Excel 2003 (Number stored as Text), using C#

There appear to be a number of suggestions to do this, non of which appear to work.
Effectively, I'm wanting to change a text value in an Excel sheet to a number (this is a cell that has been set as a number stored as text, and has a green diamond next to it).
This webpage details how to resolve the issue in Excel, through the UI, and I've recorded this as a macro below (but that's VBA)...
Including setting the value to itself:
Range allCellsRng;
string lowerRightCell = "AZ500";
allCellsRng = wSheet.get_Range("A1", lowerRightCell).Cells;
foreach (Range cell in allCellsRng)
{
if (cell.Value2.ToString().Length > 0)
{
cell.Value2 = cell.Value2;
}
}
This is a recorded VB Macro, that shows what will resolve the issue, but I'm having problems representing this in C#:
ActiveCell.FormulaR1C1 = "0"
Range("A1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
With Clear Office, the code is very easy:
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName);
foreach (Worksheet worksheet in spreadsheetDocument.Workbook.Sheets.OfType<Worksheet>())
{
foreach (Cell cell in worksheet.GetRange("A1:AZ500"))
{
string s = cell.Value as string;
if (s == null)
continue;
double d;
if (double.TryParse(s, out d))
cell.Value = d;
}
}
spreadsheetDocument.Save();
Would it not be better to change the format of the cell instead? I believe you should be able to grab the format using
range.NumberFormat
and change that to the actual format you want... You could then set the range for an entire column, or whole sheet.
Ok, so raising it as a question on here triggered a brainwave. This looks to work:
Range cellA1 = wSheet.get_Range("A1", System.Type.Missing);
cellA1.Value2 = "0";
cellA1.Copy(System.Type.Missing);
Range cellAll = wSheet.get_Range("A1:AZ500", System.Type.Missing);
cellAll.PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationAdd,
false, false);

Format an Excel column (or cell) as Text in C#?

I am losing the leading zeros when I copy values from a datatable to an Excel sheet. That's because probably Excel treats the values as a number instead of text.
I am copying the values like so:
myWorksheet.Cells[i + 2, j] = dtCustomers.Rows[i][j - 1].ToString();
How do I format a whole column or each cell as Text?
A related question, how to cast myWorksheet.Cells[i + 2, j] to show a style property in Intellisense?
Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:
IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "#";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "#";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(#"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);
Disclaimer: I own SpreadsheetGear LLC
If you set the cell formatting to Text prior to adding a numeric value with a leading zero, the leading zero is retained without having to skew results by adding an apostrophe. If you try and manually add a leading zero value to a default sheet in Excel and then convert it to text, the leading zero is removed. If you convert the cell to Text first, then add your value, it is fine. Same principle applies when doing it programatically.
// Pull in all the cells of the worksheet
Range cells = xlWorkBook.Worksheets[1].Cells;
// set each cell's format to Text
cells.NumberFormat = "#";
// reset horizontal alignment to the right
cells.HorizontalAlignment = XlHAlign.xlHAlignRight;
// now add values to the worksheet
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value.ToString();
}
}
Solution that worked for me for Excel Interop:
myWorksheet.Columns[j].NumberFormat = "#"; // column as a text
myWorksheet.Cells[i + 2, j].NumberFormat = "#"; // cell as a text
This code should run before putting data to Excel. Column and row numbers are 1-based.
A bit more details. Whereas accepted response with reference for SpreadsheetGear looks almost correct, I had two concerns about it:
I am not using SpreadsheetGear. I was interested in regular Excel
communication thru Excel interop without any 3rdparty libraries,
I was searching for the way to format column by number, not using
ranges like "A:A".
Before your write to Excel need to change the format:
xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
Dim cells As Excel.Range = xlWorkSheet.Cells
'set each cell's format to Text
cells.NumberFormat = "#"
'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
Setting the numberFormatting to # causes Excel to left-align the value, and read it as if it were text, however, it still truncates the leading zero.
Adding an apostrophe at the beginning results in Excel treating it as text and retains the zero, and then applies the default text format, solving both problems.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
Use your WorkSheet.Columns.NumberFormat, and set it to string "#", here is the sample:
Excel._Worksheet workSheet = (Excel._Worksheet)_Excel.Worksheets.Add();
//set columns format to text format
workSheet.Columns.NumberFormat = "#";
Note: this text format will apply for your hole excel sheet!
If you want a particular column to apply the text format, for example, the first column, you can do this:
workSheet.Columns[0].NumberFormat = "#";
or this will apply the specified range of woorkSheet to text format:
workSheet.get_Range("A1", "D1").NumberFormat = "#";
if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
{
myWorksheet.Cells[i + 2, j].NumberFormat = "#";
}
I know this question is aged, still, I would like to contribute.
Applying Range.NumberFormat = "#" just partially solve the problem:
Yes, if you place the focus on a cell of the range, you will read text in the format menu
Yes, it align the data to the left
But if you use the type formula to check the type of the value in the cell, it will return 1 meaning number
Applying the apostroph behave better. It sets the format to text, it align data to left and if you check the format of the value in the cell using the type formula, it will return 2 meaning text
//where [1] - column number which you want to make text
ExcelWorksheet.Columns[1].NumberFormat = "#";
//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.
//path were excel file is kept
string ResultsFilePath = #"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
ExcelApp.Visible = true;
//Looping through all available sheets
foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
{
//Selecting the worksheet where we want to perform action
ExcelWorksheet.Select(Type.Missing);
ExcelWorksheet.Columns[1].NumberFormat = "#";
}
//saving excel file using Interop
ExcelWorkbook.Save();
//closing file and releasing resources
ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(ExcelWorkbook);
ExcelApp.Quit();
Marshal.FinalReleaseComObject(ExcelApp);
You need to format the column to be a string.
You can use the link https://supportcenter.devexpress.com/ticket/details/t679279/import-from-excel-to-gridview
For converting the ExcelDataSource, you can also refer to https://supportcenter.devexpress.com/ticket/details/t468253/how-to-convert-exceldatasource-to-datatable

Categories

Resources