How can i export the Dates? - c#

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)Excel.ActiveSheet;
Excel.Visible = true;
ws.Cells[1, 1] = "Tarih";
ws.Cells[1, 2] = "Kasiyer";
ws.Cells[1, 3] = "Ucret";
ws.Cells[1, 4] = "Bilet No";
ws.Cells[1, 5] = "Firma Adı";
for (int j = 2; j < dataGridView1.Rows.Count; j++)
{
for (int i = 2; i <= 5; i++)
{
ws.Cells[j,i]=dataGridView1.Rows[j-2].Cells[i-1].Value;
}
}
Dates are not coming to First Cell in Excel . How can i do that ? please help me ? And also i have got a warning like "HRESULT özel durum döndürdü: 0x800AC472"

You can't probably take date value, it returns null and gives an error. Just for date column, you try to convert.
for (int i = 1; i < dataGridView1.Rows.Count; i++)
{
ws.Cells[i,0] = (Convert.ToDateTime(ws.Cells[i,0]).ToOADate();
}
Additionaly you can try that too.
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
range = range.get_Resize(rowCount, columnCount);
range.EntireColumn.NumberFormat = "DD/MM/YYYY";

Related

DataGridView problem (import to excel) C#

i have a problem with this part of the code more precisely with:
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
when executing this line it gives me:
System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800AC472'
private void Save()
{
Microsoft.Office.Interop.Excel._Application app = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook =
app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for(int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}

ArgumentOutOfRangeException - Import the excel file to dataGridView

I have the problem with dataGridView - Range. I am trying to insert one excel file to the dataGridView in Windows Form but something is wrong.
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fname);
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[i + 1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
rowCount = xlRange.Rows.Count;
colCount = xlRange.Columns.Count;
excelTable = createAnArray(rowCount, colCount);
for (i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
if (xlRange.Cells[i, j].Value2 != null)
{
excelTable[i - 1, j - 1] = xlRange.Cells[i, j].Value2.ToString();
// PROBLEM --->
dataGridView1.Rows[i - 1].Cells[j - 1].Value = excelTable[i - 1, j - 1];
//dataGridView1.Rows[i - 1].Cells[j - 1].Value = xlRange.Cells[i, j].Value2.ToString();
}
else
{
excelTable[i - 1, j - 1] = "";
}
}
}
Error:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll.
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

Check each value in the 3rd column of excel and if less than 4, change the row color? C#

I'm creating an Excel sheet and filling it with values using c#.
Before I save it, I want to check the 3rd column of the excel sheet and check if each value is less than 4. If it is I want to change that row to red.
Here is what I've tried so far:
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook worKbooK;
Microsoft.Office.Interop.Excel.Worksheet worKsheeT;
Microsoft.Office.Interop.Excel.Range celLrangE;
int totalcount = 0;
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
excel.DisplayAlerts = false;
worKbooK = excel.Workbooks.Add(Type.Missing);
worKsheeT = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet; worKsheeT.Name = "Model Results";
worKsheeT.Cells[1, 1] = "Name";
worKsheeT.Cells[1, 2] = "Id";
worKsheeT.Cells[1, 3] = "Sales";
for (int totalcount= 3; totalcount< dataGridView2.Columns.Count; )
{
GetSalesNumbers();
worKsheeT.Cells[totalcount, 1] = Name;
worKsheeT.Cells[totalcount, 2] = Id;
worKsheeT.Cells[totalcount, 3] = SalesNumber;
totalcount ++;
}
celLrangE = worKsheeT.Range[worKsheeT.Cells[1, 1], worKsheeT.Cells[totalcount + 5, 15]];
celLrangE.EntireColumn.AutoFit();
Excel.Range usedRange = worKsheeT.UsedRange;
Excel.Range rows = usedRange.Rows;
int count = 0;
foreach (Excel.Range row in rows)
{
if (count > 0)
{
Excel.Range firstCell = row.Cells[count,3];
string firstCellValue = firstCell.Value as String;
if (Convert.ToDouble(firstCellValue)<4)
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
count++;
}
But this doesn't work, it keeps getting the cell value as Null
This is what I ended up using, I gave up on the other code
celLrangE = worKsheeT.Range[worKsheeT.Cells[1, 1],worKsheeT.Cells[totalcount + 5, 15]];
celLrangE.EntireColumn.AutoFit();
for (int row = 3; row <= totalcount; row++)
{
if (Convert.ToDouble(worKsheeT.Cells[row, 3].Value) < 4)
{
Excel.Range rows = worKsheeT.Range[worKsheeT.Cells[row,1],worKsheeT.Cells[row,15]];
rows.Interior.Color = System.Drawing.Color.Red;
}
}

Formatting a column with EPPLUS Excel Library

I wrote a C# program to create an excel spreadsheet. The sheet has multiple columns. I want to format ONE of the columns.
aFile = new FileInfo(excelDocName); // excelDocName is a string
ExcelPackage pck = new ExcelPackage(aFile);
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = true;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
ws.Cells[1, 1].Value = "AA";
ws.Cells[1, 2].Value = "BB";
ws.Cells[1, 3].Value = "CC";
ws.Cells[1, 4].Value = "DD";
for (int row = 2; row <= 10; ++row)
for (int col = 1; col <= 4; ++col)
{
ws.Cells[row, col].Value = row * col;
}
ws.Row(1).Style.Font.Bold = true;
pck.Save();
The problem is, while it's formatting the column correct, it's also formatting other columns with the format and not just the column I specified.
I also tried:
ws.Column(1).Style.Numberformat.Format = "0.00";
Is this a bug or am I missing something?
Are you opening an existing file? It may have a format already applied to the other columns prior to you opening it. Or a template like astian said.
Clear all the formatting just in case like this:
ws.Cells["A:D"].Style.Numberformat.Format = null;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
Full unit test in EPPlus 4.0.3:
[TestMethod]
public void Format_Single_Column_Test()
{
//http://stackoverflow.com/questions/28698226/formatting-a-column-with-epplus-excel-library
var excelDocName = #"c:\temp\temp.xlsx";
var aFile = new FileInfo(excelDocName); // excelDocName is a string
if (aFile.Exists)
aFile.Delete();
ExcelPackage pck = new ExcelPackage(aFile);
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = true;
ws.Cells["A:D"].Style.Numberformat.Format = null;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
ws.Cells[1, 1].Value = "AA";
ws.Cells[1, 2].Value = "BB";
ws.Cells[1, 3].Value = "CC";
ws.Cells[1, 4].Value = "DD";
for (int row = 2; row <= 10; ++row)
for (int col = 1; col <= 4; ++col)
{
ws.Cells[row, col].Value = row*col;
}
ws.Row(1).Style.Font.Bold = true;
pck.Save();
}

How to export data table with proper formatting and write text in Excel using C# Microsoft.Office.Interop.Excel?

I'm using this function to export a data table into excel.
protected void ExportExcel(System.Data.DataTable dt)
{
if (dt == null||dt.Rows.Count==0) return;
Microsoft.Office.Interop.Excel.Application xlApp =
new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return;
}
System.Globalization.CultureInfo CurrentCI =
System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook =
workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet =
(Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
}
xlApp.Visible = true;
}
As you can see in the resulting excel image, the columns are not properly formatted i.e., the column sizes do not adapt to the databound items. How will I make the excel cells auto-adjust according to the data table?
And I also would like to add some text, maybe a header, for say maybe "System.DateTime.Now" or "data table name". How do i do this?
You should be able to format the columns like so:
Microsoft.Office.Interop.Excel.Range columns = worksheet.UsedRange.Columns;
columns.AutoFit();
You can insert a new row and place the current date as the title like so:
worksheet.Rows[1].Insert();
Excel.Range newRow = worksheet.Rows[1];
Excel.Range newCell = newRow.Cells[1];
newCell.Value = DateTime.Now.ToString("yyyy-MM-dd");
Also add this to your using statements so you don't need to use the fully qualified name every time you use an Excel object:
using Excel = Microsoft.Office.Interop.Excel;
Also, I have tidied up your method, by adding a few using statements to reduce clutter, removing some unnecessary casting and an unnesscessary check for null on the application object, just after it had been assigned:
using Excel = Microsoft.Office.Interop.Excel;
using System.Globalization;
using System.Threading;
using System.Data;
protected void ExportExcel(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0) return;
var xlApp = new Excel.Application();
//Is this used?
CultureInfo CurrentCI = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Range range
Excel.Workbook workbook = workbooks.Add();
Excel.Worksheet worksheet = workbook.Worksheets[1];
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
for (var i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
for (var r = 0; r < dt.Rows.Count; r++)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
rowRead++;
//is this used?
percent = ((float)(100 * rowRead)) / totalCount;
}
Microsoft.Office.Interop.Excel.Range columns = worksheet.UsedRange.Columns;
columns.AutoFit();
worksheet.Rows[1].Insert();
Excel.Range newRow = worksheet.Rows[1];
Excel.Range newCell = newRow.Cells[1];
newCell.Value = DateTime.Now.ToString("yyyy-MM-dd");
xlApp.Visible = true;
}

Categories