C# Gridview to Excel with number formatting and table line - c#

Hello I want import my data in Gridview to Excel, my data in Gridview is "00, 02, 04" but in excel my data change to "0, 2, 4" I dont wont it, i want my data in Excel like same in Gridview.And How to move rows to new columns, for exp i have 160 rows data, i want in excel split to 3 columns, 1 column have 40 rows. This my code :
private void exToExcel()
{
if (RekapdataGridView.Rows.Count > 0)
{
Microsoft.Office.Interop.Excel.Application XcelApp = new Microsoft.Office.Interop.Excel.Application();
XcelApp.Application.Workbooks.Add(Type.Missing);
//XcelApp.Cells[5,2].NumberFormat = "00";
XcelApp.Cells[1, 1] = "Tanggal";
XcelApp.Cells[1, 2] = labelTglRekap.Text;
XcelApp.Cells[2, 1] = "Kode Pemain";
XcelApp.Cells[2, 2] = labelKodePemain.Text;
XcelApp.Cells[4, 1] = "No";
int x = RekapdataGridView.RowCount;
for (int y = 1; y <= RekapdataGridView.RowCount; y++)
{
XcelApp.Cells[4+y, 1] = y;
}
for (int i = 2; i < RekapdataGridView.Columns.Count + 2; i++)
{
XcelApp.Cells[4, i] = RekapdataGridView.Columns[i - 2].HeaderText;
}
for (int i = 0; i < RekapdataGridView.Rows.Count; i++)
{
for (int j = 0; j < RekapdataGridView.Columns.Count; j++)
{
XcelApp.Cells[i + 5, j + 2] =string.Format("{0:00}", RekapdataGridView.Rows[i].Cells[j].Value);
}
}
XcelApp.Columns.AutoFit();
XcelApp.Visible = true;
}
}
This is my data in excel :
I want my data can showing like this image :
Sorry if my English is bad, i hope someone can help me.

You nearly had it with
XcelApp.Cells[5,2].NumberFormat = "00";
Just change it to
XcelApp.Cells[5,2].NumberFormat = "#";
Which will make the cell format be 'Text' instead of number. Excel always tries to simplify numbers from my experience.
Just don't forget to do it to ALL cells you are writing into.
Hope this helps!

Related

How I make this For Loop faster for my DataTable to Excel export?

Im currently exporting my DataTable to an Excel File and for that I've got that loop:
for (int i = 0; i < newsletter.Rows.Count; i++)
{
for (int j = 0; j < newsletter.Columns.Count; j++)
{
if (j == 2)
{
//exrngKopf = oWS.get_Range("A1", "A11");
oWS.Hyperlinks.Add(oWS.UsedRange.Item[i + 1, j + 1], newsletter.Rows[i][j + 8].ToString(), "", "", newsletter.Rows[i][j].ToString());
//MessageBox.Show("2");
j++;
}
else
{
oWS.Cells[i + 1, j + 1] = newsletter.Rows[i][j].ToString();
}
}
}
Note: The j == 2 is the part where it is an Hyperlink and thats why I add this difference to avoid Crashes.
And that Code is working and he is making the Excel Sheet correct, but the DataTable has like more then 10.000 data, so it works after 30 minute of Loading, someone an Idea how to make it faster ?

Importing csv file into Excel using EPPlus losing trailing zeroes on data

I'm using C# and EPPlus to import .csv data into a workbook. My only issue is that after the import into Excel, I am losing trailing zeroes on the data.
For example:
in the .CSV file, the data is this: 1250.80
in the .xlsx file, the data ends up being 1250.8
Seems minor but I need this to compare workbook to workbook and not see all of these diffs.
Here is the read routine
string[] csvInputfile = File.ReadAllLines(filePathName);
Here is how I am trying to put double quotes around the data
for (int idx = 0; idx < csvInputfile.Length; idx++)
{
csvInputfile[idx] = csvInputfile[idx].Replace(",", ",\"");
}
Here I am writing the contents to the Excel instance
for (int i = 0; i < csvInputfile.Length; i++)
{
ExcelWorksheet curWorksheet = excelPackage.Workbook.Worksheets.Add(csvInputfile[outerLoopCnt]);
for (int j = 0; j < csvInputfile.Length; j++)
{
innerLoopCnt++;
curWorksheet.Cells[j + 1, 1, j + 1, 100].Style.Numberformat.Format = "#";
curWorksheet.Cells[j + 1, 1].LoadFromText(csvInputfile[innerLoopCnt], format);
if (csvInputfile[innerLoopCnt + 1] == "")
{
outerLoopCnt = innerLoopCnt + 2;
innerLoopCnt += 2;
break;
}
}
if (innerLoopCnt == csvInputfile.Length)
{
break;
}
}
Here I save the file:
excelPackage.SaveAs(file);
This is the general idea and its not working very well. This is a crude approach but I'm not sure how else to make this work, I would appreciate any help

Get Data From Excel - Index exceeds bounds

I am trying to get data from an Excel file. I know that indexing in excel starts from 1, but still when reading a simple matrix, I am getting an Index exceeds bounds error.
Here is a simple method I'm using:
public static string[,] ReadFromExcel(Worksheet excelSheet)
{
if (excelSheet == null) return new string[1,1];
Microsoft.Office.Interop.Excel.Range xlRange = excelSheet.UsedRange;
int firstRow = xlRange.Row;
int firstColumn = xlRange.Column;
int lastRow = xlRange.Row + xlRange.Rows.Count - 1;
int lastColumn = xlRange.Column + xlRange.Columns.Count - 1;
string[,] data = new string[xlRange.Rows.Count - xlRange.Row, xlRange.Columns.Count - xlRange.Column];
for (int i= 0; i<= lastRow - firstRow; i++)
{
for (int j= 0; j <= lastColumn - firstColumn; j++)
{
data[i,j] = (string)(excelSheet.Cells[firstRow + i][firstColumn + j] as Range).Value;
//When I try to read values I get an error
System.Windows.MessageBox.Show(data[i, j]);
}
}
return data;
}
What am I missing?
The size of your "data" array should match the number of rows & columns:
string[,] data = new string[xlRange.Rows.Count, xlRange.Columns.Count];
Although the start index for Excel Interop is 1, rather than zero, the count is correct & you don't need to subtract the start row & column.

Epplus conditional formatting based on a rule

How can we add three icon sets to each cell in excel using epplus conditional formatting. I'm using following code to add three icon set:
using (ExcelRange scoreRange = workSheet.Cells[1, 2, 1, 10])
{
ExcelAddress rangeAddress = new ExcelAddress(scoreRange.Address);
var ruleIconSet = workSheet.ConditionalFormatting.AddThreeIconSet(rangeAddress, eExcelconditionalFormatting3IconsSetType.Arrows); // This calculates based on the value in the range
}
I want to create a rule like if value in a cell is less than 0, the green color icon should be displayed, if value is greater than 0, the red color icon should be displayed.
What should be the rule statement that can perform this stuff?
for(int j =2; j <=9; j++) //Loop through columns
{
for(int i = 3; i <= 12; i++) // Loop through rows
{
// gets only the current cell as range
ExcelRange rng = worksheet.Cells[i, j, i, j];
ExcelAddress address = new ExcelAddress(rng.Address);
// Get the value of the current cell
if(Convert.ToDouble(worksheet.Cells[i, j].Value) >= 4.0)
{
var v = worksheet.ConditionalFormatting.AddThreeIconSet(address, eExcelconditionalFormatting3IconSetType.Arrows);
v.Reverse = true;
v.Icon1.Type = eExcelConditionalFormattingValueObjectType.Num;
}
else if(Convert.ToDouble(workSheet.Cells[i, j].Value) > 1.0 && Convert.ToDouble(workSheet.Cells[i, j].Value) < 4.0)
{
var v = worksheet.ConditionalFormatting.AddThreeIconSet(address , eExcelconditionalFormatting3IconsSetType.Arrows);
v.Icon3.Type = eExcelConditionalFormattingValueObjectType.Num;
}
else (Convert.ToDouble(workSheet.Cells[i, j].Value) < 1.0)
{
var v = worksheet.ConditionalFormatting.AddThreeIconSet(address , eExcelconditionalFormatting3IconsSetType.Arrows);
v.Icon2.Type = eExcelConditionalFormattingValueObjectType.Num;
}
}
}
This works for me.

export datagridview to excel with interop

I want to ask if there is another way to export from datagridview to excel. Because i did it with interop and it's very slow for big file. Now i want to do it with interop too but it should load data quicker.
the code i used:
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
xlWorkSheet1.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet1.Cells[i + 2, j + 1] = cell.Value;
}
}
Now i would like to export not cell for cells, but row for rows. Something with object[,] values1
my code for export from excel to datatable:
object[,] values1 = (object[,])xlWorksheet1.UsedRange.Value2; // excelTb1
for (int k = 0; k < values1.GetLength(1); )
{
excelTb1.Columns.Add((string)values1[1, ++k]);
}
object[] singleDValue = new object[values1.GetLength(1)];
for (int i = 1; i < values1.GetLength(0); i++)
{
for (int k = 0; k < values1.GetLength(1); )
{
singleDValue[k] = values1[i + 1, ++k];
}
excelTb1.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}
Can someone show me how to do it from datagridview to excel?
I think this article may help you much, it can export datagridview to excel with the max data of 6000 rows relatively fast in speed.
9 Solutions to Export Data to Excel for ASP.NET

Categories

Resources