I am having a formatting issue when exporting my data table to Excel. The data is exported as it should, however if you look at my image, sometimes the cell height is increased and I am not sure why. I want the data to look the same from row to row. This is the syntax I am using to export
for (var i = 0; i < tbl.Columns.Count; i++)
workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
for (var i = 0; i < tbl.Rows.Count; i++)
{
for (var j = 0; j < tbl.Columns.Count; j++)
workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
}
And here is an image that shows my formatting issues that I want to find a way to overcome. Can someone show me what syntax I need in order to have all row height/width the same?
Issue Image
EDIT
I tried this, but it throws an error and does not format as needed
The error is
System.Exception
Excel.Range range1 = workSheet.get_Range("A2", "S2000");
range1.EntireRow.Height.Value = 15;
You are over complicating it. Just use the UsedRange property. If workSheet is your actual variable name and 15 is the actual height you want to set, the below will work:
workSheet.UsedRange.EntireRow.RowHeight = 15;
Related
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
I have a DataGridView which I put on a form using the designer. I'm trying to display some data by programmatically creating rows. The code is below. This DataGridView displays nothing at all, it might as well be an empty label or panel. I've looked at other questions regarding empty DataGridViews and tried all the suggestions. One common suggestion is "Just set AutoGenerateColumns to true, it will solve the problem." That did not work. I've tried implementing a DataTable and binding to the DataSource on the DataGridView. That did not work either.
Using the debugger in VisualStudio, I tried looking at the row properties/column properties/cell properties (within each row). The row and cell properties both have a "Displayed" property, which is set to false. This seems to be a read-only property, I can't set it to true (I get an error when I try). Apparently this property can be set to true or false to show or hide rows or cells, but I can't set it to anything.
After trying a lot of things, I ended up with the minimal test code below, which should work, but still doesn't.
What am I doing wrong?
int M = 2, N = 2;
dgvSpreadSheet.AutoGenerateColumns = true;
dgvSpreadSheet.ColumnCount = N;
dgvSpreadSheet.Rows.Clear();
for (int ix = 0; ix < N; ix++)
dgvSpreadSheet.Columns[ix].Name = "Column " + (ix + 1).ToString();
for (int ix = 0; ix < M; ix++)
{
string[] row = new string[N];
for (int j = 0; j < N; j++)
{
row[j] = "Test";
}
dgvSpreadSheet.Rows.Add(row);
dgvSpreadSheet.Rows[ix].HeaderCell.Value = "Header" + (ix + 1).ToString();
}
dgvSpreadSheet.RowHeadersWidth = 200;
dgvSpreadSheet.RowHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.True;
dgvSpreadSheet.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dgvSpreadSheet.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
Using EPPLus library, I'm trying to autofit very long strings in xlsx cells this way:
worksheet.Cells.AutoFitColumns();
Rows: 1000
Columns: 10
For 2 columns, I'm expecting around 6000 character in each cell.
In this scenario, AutoFitColumns method generates the following exception:
Message: A generic error occurred in GDI+.
StackTrace: at
System.Drawing.Graphics.MeasureString(String text, Font font, SizeF
layoutArea, StringFormat stringFormat) at
System.Drawing.Graphics.MeasureString(String text, Font font, Int32
width, StringFormat format) at
OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth,
Double MaximumWidth) at
OfficeOpenXml.ExcelRangeBase.AutoFitColumns()...
EDIT
Here is my full code:
using (ExcelPackage package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Setup the first row with headers
for (int j = 0; j < fields.Length; j++)
{
worksheet.Cells[1, j + 1].Value = fields[j];
}
Color colFromHex = ColorTranslator.FromHtml("#B4B4B4");
worksheet.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Row(1).Style.Fill.BackgroundColor.SetColor(colFromHex);
// Insert new rows
for (int i = 0; i < elements.Count; i++)
{
// this will return List<object>
var properties = elements[i].GetPatentProperties();
for (int j = 0; j < properties.Count; j++)
{
worksheet.Cells[i + 2, j + 1].Value = properties[j];
}
}
// This will throw an exception for big number of elements: ~ 1000 element
worksheet.Cells.AutoFitColumns();
worksheet.Cells.Style.WrapText = true;
//worksheet.Cells[autosize].Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous;
package.Save();
}
Note that for the same list of elements, if I remove worksheet.Cells.AutoFitColumns();, I will get my xlsx file without exception.
Is it possible to overcome this issue?
Have you tried setting min and max col sizes?
ws.Cells.AutoFitColumns(10, 60);
I'm trying to get a selected datagridview row to a datatable.
With the following code I am able to send the selectedrow over, however when trying to send a second row to the datatable, it adds an empty row but overwrites the first row in the datatable.
for (int i = 0; i < dataGridview.SelectedRows.Count; i++)
{
DT1.Rows.Add();
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
DT1.Rows[0][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
}
As expected it enters the row on index 0, so i tried the folowing to get to the last row
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
int rowcount = DT1.Rows.Count;
DT1.Rows[rowcount][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
This gives me an error that the row does not exist, what should be the solution to add a second row instead of replacing?
You've got other problems in your code. Namely, if your user selects the same rows in different calls to this code, you will insert duplicates.
Fix rowcount, changing it to rowcount-1. Then review your design. Come up with an approach to prevent duplicate insertions (unless you really want that).
You have a problem in rowcount
Rowcount gives you total no of rows but rowindex always starts with 0
ie rowindex = rowcount-1
use this
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
int rowcount = DT1.Rows.Count;
DT1.Rows[rowcount-1][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
DT1.Rows[i][j] = dataGridview.SelectedRows[i].Cells[j].Value,ToString();
Try this! Your outer loop is already keeping track of the rows in your tables so there's no need to mess with the row count.
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