What should I write to see images that coming from database in all rows
I want to see the image in [i,2] row.
Here is my code
int i = 2;
foreach (var item in chartProduct)
{
ws.Cells[i, 1].Value = item.Id;
ws.Cells[i, 1].Style.Font.Bold = true;
ws.Cells[i, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
string imagePath = _hostingEnvironment.WebRootPath + $#"\images\product\" + item.ImageUrl;
FileInfo img = new FileInfo(imagePath);
ExcelPicture pic = ws.Drawings.AddPicture("img", img);
pic.SetSize(50,50);
ws.cells[i,2].value = ??
ws.Cells[i, 3].Value = item.Material.Code;
ws.Cells[i, 3].Style.Font.Bold = true;
ws.Cells[i, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 4].Value = item.Material.Name;
ws.Cells[i, 4].Style.Font.Bold = true;
ws.Cells[i, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 5].Value = item.Code;
ws.Cells[i, 5].Style.Font.Bold = true;
ws.Cells[i, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 6].Value = item.Name;
ws.Cells[i, 6].Style.Font.Bold = true;
ws.Cells[i, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
i++;
}
in this part what should i do ??
string imagePath = _hostingEnvironment.WebRootPath + $#"\images\product\" + item.ImageUrl;
FileInfo img = new FileInfo(imagePath);
ExcelPicture pic = ws.Drawings.AddPicture("img", img);
pic.SetSize(50,50);
ws.cells[i,2].value = ??
Try this solution,Hope It helps.
int i = 2;
foreach (var item in chartProduct)
{
ws.Cells[i, 1].Value = item.Id;
ws.Cells[i, 1].Style.Font.Bold = true;
ws.Cells[i, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Column(2).Width = 50;
ws.Row(i).Height = 50;
// string imagePath = _hostingEnvironment.WebRootPath +
//$#"\images\product\" + item.ImageUrl;
string filePath= "~/images/product/" + item.ImageUrl;
AddPictures(ws, filePath,i,2);
ws.Cells[i, 3].Value = item.Material.Code;
ws.Cells[i, 3].Style.Font.Bold = true;
ws.Cells[i, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 4].Value = item.Material.Name;
ws.Cells[i, 4].Style.Font.Bold = true;
ws.Cells[i, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 5].Value = item.Code;
ws.Cells[i, 5].Style.Font.Bold = true;
ws.Cells[i, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 6].Value = item.Name;
ws.Cells[i, 6].Style.Font.Bold = true;
ws.Cells[i, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
i++;
}
separate method to add Picture
public void AddPictures(ExcelWorksheet ws, string filePath,int row,int col)
{
Image image = Image.FromFile(filePath);
OfficeOpenXml.Drawing.ExcelPicture pic =ws.Drawings.AddPicture(string.Format("Pic{0}",row), image);
pic.SetPosition(row-1, 0,0,0);
pic.SetSize(50,50);
}
Related
I am using the EPPlus library to read a datetime value from a sql table and export it to excel. The export works fine but when I view the excel file the date shows as a double instead of dateime I have placed my code below
workSheet.Row(1).Height = 20;
workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
workSheet.Row(1).Style.Font.Bold = true;
workSheet.Cells[1, 1].Value = "UploadId";
workSheet.Cells[1, 2].Value = "ClientId";
workSheet.Cells[1, 3].Value = "Email1";
workSheet.Cells[1, 4].Value = "Email2";
workSheet.Cells[1, 5].Value = "Email3";
workSheet.Cells[1, 6].Value = "Email4";
workSheet.Cells[1, 7].Value = "DateStamp";
//Body of table
//
int recordIndex = 2;
foreach (var exportData in dataToExport)
{
//double date = double.Parse(date);
//string sDate = (workSheet.Cells[recordIndex, 7]).Value.ToString();
//double date = double.Parse(sDate);
//var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");
workSheet.Cells[recordIndex, 1].Value = UploadId;
workSheet.Cells[recordIndex, 2].Value = exportData.ClientId;
workSheet.Cells[recordIndex, 3].Value = exportData.Email1;
workSheet.Cells[recordIndex, 4].Value = exportData.Email2;
workSheet.Cells[recordIndex, 5].Value = exportData.Email3;
workSheet.Cells[recordIndex, 6].Value = exportData.Email4;
workSheet.Cells[recordIndex, 7].Value = exportData.DateStamp;
recordIndex++;
}
Something like this should do it;
workSheet.Cells[recordindex, 7].Style.Numberformat.Format = "yyyy-MM-dd";
I have been working on Excel Sheet Formatting using EPPlus. I am able to create group when the Excel Sheet is in a ordered one .But if the input comes unordered and I have to group then I am facing issue.
The Excel input looks like in the problematic sceario:
Field1 Field2 Field3
1 XYZ ABC
3.1 PRQ SDE
1.1 AB ST
1.2 MN RT
like wise and all 1 related row should be at one group like in ascending order.
I have written the below which if sorted works fine but not able to figure out if the input is jumbled up/ not sorted.
Here is my code.
Thanks for your help.
namespace EPPlusTestDemo {
class Program
{
static void Main(string[] args)
{
// Set the File name and get the output directory
var fileName = "Example-File-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = #"C:\Users\asder\Desktop\outpath\" + fileName;
// Create the file using the FileInfo object
var file = new FileInfo(outputDir);
using (var package = new ExcelPackage(file))
{
// Adding a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Example list - " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
// Header part
worksheet.Cells["A1"].Value = "Field1";
worksheet.Cells["B1"].Value = "Field2";
worksheet.Cells["C1"].Value = "Field3";
worksheet.Cells["D1"].Value = "Field4";
worksheet.Cells["E1"].Value = "Field5";
worksheet.Cells["A1:E1"].Style.Font.Bold = true;
// The row number
int initialRowNum = 2;
int rowNumber = initialRowNum;
#region input_toExcel
// Filling the data from the 2nd row of the excel sheet
worksheet.Cells[rowNumber, 1].Value = "1";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.1";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.2";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.1";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.2";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
#endregion
// Grouping after comparing the Cell Value
for ( var rowIndex = initialRowNum; worksheet.Row(rowIndex) != null; rowIndex++)
{
// Checking for NULL in the Excel Sheet
var comapreable = worksheet.Cells[rowIndex, 1].GetValue<string>();
// Group Counter
int count = 0;
if (comapreable != null)
{
Regex regexIntegral = new Regex(#"\d");
Match matchIntegral = regexIntegral.Match(comapreable);
Regex regexDouble = new Regex(#"([1-9]+)\.([1-9]+)");
Match matchDouble = regexDouble.Match(comapreable);
// Checking if the Cell of the Excel sheet contains any integral value
if ( matchIntegral.Success == true )
{
count++; // Incrementing the Group Level Counter
// Checking if the Cell contains the decimal values
if ( matchDouble.Success == true )
{
worksheet.Row(rowIndex).OutlineLevel = count;
worksheet.Row(rowIndex).Collapsed = true;
}
}
}
else
{
break;
}
}
// Saving the File
package.Save();
}
// Console.ReadKey();
}
} }
I have found out the below findings on my question.Please find the code below.
Please do comment if you feel there are more good solutions. Thanks
class Program
{
static void Main(string[] args)
{
// Set the File name and get the output directory
var fileName = "Example-File-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = #"E:\C#Programming\ExcelFormattingProject\outpath\" + fileName;
DataTable dt = new DataTable();
// Create the file using the FileInfo object
var file = new FileInfo(outputDir);
using (var package = new ExcelPackage(file))
{
// Adding a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Example list - " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
// Header part
worksheet.Cells["A1"].Value = "Field1";
worksheet.Cells["B1"].Value = "Field2";
worksheet.Cells["C1"].Value = "Field3";
worksheet.Cells["D1"].Value = "Field4";
worksheet.Cells["E1"].Value = "Field5";
worksheet.Cells["A1:E1"].Style.Font.Bold = true;
// The row number
int initialRowNum = 2;
int rowNumber = initialRowNum;
#region input_toExcel
// Filling the data from the 2nd row of the excel sheet
worksheet.Cells[rowNumber, 1].Value = "1";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.1";
worksheet.Cells[rowNumber, 2].Value = "Item2.1";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.2";
worksheet.Cells[rowNumber, 2].Value = "Item1.2";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.1";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.2";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
#endregion
// Need to fetch the data as a row or recorset and then sort it and place it to a new Excel
//worksheet.Cells["A2:A11"].Style.Numberformat.Format = "#0\\.00";
for (var rowIndex = 1;rowIndex < 11; rowIndex++)
{
var colIndex = 1;
for (; colIndex <= 5;)
{
// Filling the First Row of the DataTable with the Field Name as on the Excel Sheet
if (rowIndex == 1)
{
dt.Columns.Add(new DataColumn(worksheet.Cells[rowIndex, colIndex].Text));
}
else
{
dt.Columns.Add(new DataColumn());
}
colIndex++;
}
dt.Rows.Add(dt.NewRow());
}
// Inserting Values in the DataTable
for (var rowIndex = 1; rowIndex < 11; rowIndex++)
{
// Filling the DataTable with Excel Contents
for (var colIndex = 1; colIndex <= 5;)
{
dt.Rows[rowIndex - 1][colIndex - 1] = worksheet.Cells[rowIndex+1, colIndex].Text;
colIndex++;
}
}
// Sorting the DataTable
DataTable dtOut = null;
dt.DefaultView.ToTable(false, "Field1", "Field2", "Field3", "Field4", "Field5");
dt.DefaultView.Sort = "Field1";
dtOut = dt.DefaultView.ToTable(false, "Field1", "Field2","Field3","Field4","Field5");
// Exporting the DataTable to the WorkSheet of the Excel
worksheet.Cells["A1"].LoadFromDataTable(dtOut, true);
#endregion
// Grouping after comparing the Cell Value
for ( var rowIndex = 2; worksheet.Row(rowIndex) != null; rowIndex++)
{
// Checking for NULL in the Excel Sheet
var comapreable = worksheet.Cells[rowIndex, 1].GetValue<string>();
// Group Counter
int count = 0;
if (comapreable != null)
{
Regex regexIntegral = new Regex(#"\d");
Match matchIntegral = regexIntegral.Match(comapreable);
Regex regexDouble = new Regex(#"([1-9]+)\.([1-9]+)");
Match matchDouble = regexDouble.Match(comapreable);
// Checking if the Cell of the Excel sheet contains any integral value
if ( matchIntegral.Success == true )
{
count++; // Incrementing the Group Level Counter
// Checking if the Cell contains the decimal values
if ( matchDouble.Success == true )
{
worksheet.Row(rowIndex).OutlineLevel = count;
worksheet.Row(rowIndex).Collapsed = true;
}
}
}
else
{
break;
}
}
// Saving the File
package.Save();
}
// Console.ReadKey();
}
}
I have been stuck on this issue for a a day or so and need some help. In my application, I have some data in a listview, which is
public void OnHostPing(HostPinger host)
{
if (InvokeRequired)
{
Invoke(new OnPingDelegate(OnHostPing), new object[] { host });
return;
}
lock (_table)
{
ListViewItem item = (ListViewItem)_table[host.ID];
if (item != null)
{
item.SubItems[0].Text = host.HostIP.ToString();
item.SubItems[1].Text = host.HostName;
item.SubItems[2].Text = host.HostDescription;
item.SubItems[3].Text = host.StatusName;
item.SubItems[4].Text = host.SentPackets.ToString();
item.SubItems[5].Text = host.ReceivedPackets.ToString();
item.SubItems[6].Text = PercentToString(host.ReceivedPacketsPercent);
item.SubItems[7].Text = host.LostPackets.ToString();
item.SubItems[8].Text = PercentToString(host.LostPacketsPercent);
item.SubItems[9].Text = host.LastPacketLost ? "Yes" : "No";
item.SubItems[10].Text = host.ConsecutivePacketsLost.ToString();
item.SubItems[11].Text = host.MaxConsecutivePacketsLost.ToString();
item.SubItems[12].Text = host.RecentlyReceivedPackets.ToString();
item.SubItems[13].Text = PercentToString(host.RecentlyReceivedPacketsPercent);
item.SubItems[14].Text = host.RecentlyLostPackets.ToString();
item.SubItems[15].Text = PercentToString(host.RecentlyLostPacketsPercent);
item.SubItems[16].Text = host.CurrentResponseTime.ToString();
item.SubItems[17].Text = host.AverageResponseTime.ToString("F");
item.SubItems[18].Text = host.MinResponseTime.ToString();
item.SubItems[19].Text = host.MaxResponseTime.ToString();
item.SubItems[20].Text = DurationToString(host.CurrentStatusDuration);
item.SubItems[21].Text = DurationToString(host.GetStatusDuration(HostStatus.Alive));
item.SubItems[22].Text = DurationToString(host.GetStatusDuration(HostStatus.Dead));
item.SubItems[23].Text = DurationToString(host.GetStatusDuration(HostStatus.DnsError));
item.SubItems[24].Text = DurationToString(host.GetStatusDuration(HostStatus.Unknown));
item.SubItems[25].Text = PercentToString(host.HostAvailability);
item.SubItems[26].Text = DurationToString(host.TotalTestDuration);
item.SubItems[27].Text = DurationToString(host.CurrentTestDuration);
}
else
{
item = new ListViewItem(new string[]
{
host.HostIP.ToString(), host.HostName, host.HostDescription,
host.StatusName,
host.SentPackets.ToString(),
host.ReceivedPackets.ToString(), PercentToString(host.ReceivedPacketsPercent),
host.LostPackets.ToString(), PercentToString(host.LostPacketsPercent),
host.LastPacketLost ? "Yes" : "No",
host.ConsecutivePacketsLost.ToString(), host.MaxConsecutivePacketsLost.ToString(),
host.RecentlyReceivedPackets.ToString(), PercentToString(host.RecentlyReceivedPacketsPercent),
host.RecentlyLostPackets.ToString(), PercentToString(host.RecentlyLostPacketsPercent),
host.CurrentResponseTime.ToString(), host.AverageResponseTime.ToString("F"),
host.MinResponseTime.ToString(), host.MaxResponseTime.ToString(),
DurationToString(host.CurrentStatusDuration),
DurationToString(host.GetStatusDuration(HostStatus.Alive)),
DurationToString(host.GetStatusDuration(HostStatus.Dead)),
DurationToString(host.GetStatusDuration(HostStatus.DnsError)),
DurationToString(host.GetStatusDuration(HostStatus.Unknown)),
PercentToString(host.HostAvailability),
DurationToString(host.TotalTestDuration),
DurationToString(host.CurrentTestDuration)
});
What I can't seem to figure out is, how to get that data exported to Excel? I am able to export static data to Excel with this code
public static string RunSample1(DirectoryInfo outputDir)
{
if (!outputDir.Exists) throw new Exception("outputDir does not exist!");
FileInfo newFile = new FileInfo(outputDir.FullName + #"\sample1.xlsx");
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(outputDir.FullName + #"\sample1.xlsx");
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Current Devices");
//Add the headers
//worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 1].Value = "";
worksheet.Cells[1, 2].Value = "Product";
worksheet.Cells[1, 3].Value = "Quantity";
worksheet.Cells[1, 4].Value = "Price";
worksheet.Cells[1, 5].Value = "Value";
//Add some items...
worksheet.Cells["A2"].Value = 12001;
worksheet.Cells["B2"].Value = "Nails";
worksheet.Cells["C2"].Value = 37;
worksheet.Cells["D2"].Value = 3.99;
What I can't figure out is how to get those listview items in to the spreadsheet cells instead of static data. ListViewItems doesn't seem to yield the properties I would expect. Can someone help me out a bit here?
I found a solution using Microsoft.Office.Interop.Excel instead of trying to use the EPPlus solution.
Hi there i have this code to export my data gridview to excel
and my problem is that, the gridview shows a 12hr format but when i export it to excel it shows a 24hr format, how ca i make it into 12 hr format? thank you.
DataSet ds = (DataSet)ViewState["audit"];
DataTable dt = new DataTable();
dt = ds.Tables[0];
Table table = new Table();
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
for (int i = 0; i < AuditTrailGV.HeaderRow.Cells.Count; i++)
{
AuditTrailGV.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
AuditTrailGV.HeaderRow.Style.Add("border-color", "#FFFFFF");
int j = 1;
foreach (GridViewRow gvrow in AuditTrailGV.Rows)
{
//gvrow.BackColor = color.White;
gvrow.Style.Add("background-color", "#FFFFFF");
gvrow.Style.Add("border-color", "#bfc2c7");
if (j <= AuditTrailGV.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
else
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
}
j++;
}
foreach (GridViewRow row in AuditTrailGV.Rows)
{
table.Rows.Add(row);
}
TableHeaderCell header = new TableHeaderCell();
header.RowSpan = 1;
header.ColumnSpan = 6;
header.Text = "Inventory Accounting and Control System";
header.Font.Bold = true;
header.HorizontalAlign = HorizontalAlign.Center;
header.VerticalAlign = VerticalAlign.Middle;
header.Font.Size = 20;
TableRow headerrow = new TableRow();
headerrow.Cells.Add(header);
TableHeaderCell header2 = new TableHeaderCell();
header2.RowSpan = 1;
header2.ColumnSpan = 6;
header2.Text = "Audit Trail";
header2.Font.Bold = true;
header2.HorizontalAlign = HorizontalAlign.Center;
header2.VerticalAlign = VerticalAlign.Middle;
header2.Font.Size = 16;
TableRow headerrow2 = new TableRow();
headerrow2.Cells.Add(header2);
TableHeaderCell header3 = new TableHeaderCell();
header3.RowSpan = 1;
header3.ColumnSpan = 6;
header3.Text = DatefromTxtBox.Text + " to " + DatetoTxtBox.Text;
header3.Font.Bold = true;
header3.HorizontalAlign = HorizontalAlign.Center;
header3.VerticalAlign = VerticalAlign.Middle;
header3.Font.Size = 16;
TableRow headerrow3 = new TableRow();
headerrow3.Cells.Add(header3);
table.Rows.AddAt(0, headerrow);
table.Rows.AddAt(1, headerrow2);
table.Rows.AddAt(2, headerrow3);
table.Rows.AddAt(3, AuditTrailGV.HeaderRow);
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "IACSAuditTrail" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Write(sw.ToString());
Response.End()
This it what it looks
but this is what i looks when i export it to excel :(
The only way to save date format is to pre-format the date field as text and then export to excel. To do this,
string style = #"<style> TD { mso-number-format:\#; } </style> ";
Response.write(style);
//Code to Export Control
Panel1.RenderControl(htmlWrite);
you can refer to below link for more information
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
I want to name each column in the first row of the excel sheet, I get an exception on the first line of naming the columns. Please advise?
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;
int i = 2;
int j = 1;
if (comboBox1.Text == "Brickcom")
{
try
{
ws.Rows[j, 1] = "Category";
ws.Rows[j, 2] = "Part Number";
ws.Rows[j, 3] = "TradePrice";
ws.Rows[j, 4] = "Product";
ws.Rows[j, 5] = "Resolution";
ws.Rows[j, 6] = "Included Accessories";
ws.Rows[j, 7] = "Major Acc Price";
foreach (ListViewItem comp in listView1.Items)
{
ws.Cells[i, j] = comp.Text.ToString();
foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)
{
ws.Cells[i, j] = drv.Text.ToString();
j++;
}
j = 1;
i++;
}
xla.Visible = true;
}
catch
{
MessageBox.Show("Export did not work");
}
}
Try this:
ws.Cells[j, 1] = "Category";
ws.Cells[j, 2] = "Part Number";
ws.Cells[j, 3] = "TradePrice";
...
i would use stream writer :
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "CSV|*.csv";
savefile.RestoreDirectory = true;
savefile.ShowDialog();
string filename = savefile.FileName;
if (filename != "")
{
StreamWriter ofile = new StreamWriter(filename);
ofile.WriteLine("Category, Part Number, TradePrice, ..."); //just separate using a comma ,
//your complete writings here
ofile.Close(); //close the streamwriter and you're done
}
good luck