Add text to row 1 in excel export listview - c#

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

Related

How to color columns when exporting to Excel?

I have the following code to export data to an Excel sheet. I need your help to know how I can color the sheet columns in other colors?
System.Data.DataTable dit = null;
try
{
dit = BindGrid();
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dit, "Students");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Download.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
catch (Exception Ex)
{
}
finally
{
dit = null;
}
using Excel = using Microsoft.Office.Interop.Excel
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
string path = excelFilename + ".xlsx";
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();
}
worksheet.Cells[i + 2, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
}
workbook.SaveCopyAs(path);
workbook.Saved = true;
workbook.Close();
app.Quit();
}

Excel Sheet Not Saving Data in Sheet 1

I Excel File with 2 sheets, First sheet named as "PM" and second Sheet named as "km" when i try to enter data to sheet 1 from textboxes it successfully done but when i tried to enter data in sheet 2.. sheet 1 back to its original state(Empty)..
I checked the code i made at first 1 worksheet "xlsht" for both sheets but data not updated on both sheets then i made 2 functions with 2 worksheets but the problem is same, any idea why?
My Code:
protected void PM_Sheet1()
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Worksheet xlsht = new Worksheet();
string path = #"D:\test.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["PM"];
xlsht.Cells[11, 2] = UserNameTxt.Text + "#rasatop.com";
xlsht.Cells[11, 4] = UserNameTxt.Text;
xlsht.Cells[14, 2] = SerialTxt.Text;
xlsht.Cells[16, 2] = WLANMacTxt.Text;
xlsht.Cells[16, 3] = LANMacTxt.Text;
xlsht.Cells[16, 4] = IPTxt.Text;
xlsht.Cells[14, 5] = ComputerTxt.Text;
xlsht.Cells[16, 5] = BarcodeTxt.Text;
xlsht.Cells[18, 5] = CPUTxt.Text.Substring(0, 26);
xlsht.Cells[18, 4] = VGATxt.Text;
xlsht.Cells[18, 3] = RAMTxt.Text;
xlsht.Cells[27, 4] = OSTxt.Text;
xlsht.Cells[5, 4] = System.DateTime.Today;
xlsht.Cells[26, 4] = System.DateTime.Today;
xlsht.Cells[9, 5] = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
xlsht.SaveAs(#"D:\test1.xlsx");
}
catch (Exception)
{
MessageBox.Show(#"Make Sure test.xlsx file in D:\ Drive");
}
}
protected void PM_Sheet2()
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Worksheet xlsht = new Worksheet();
string path = #"D:\test1.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["km"];
xlsht.Cells[4, 2] = System.DateTime.Today;
xlsht.Cells[6, 2] = UserNameTxt.Text;
xlsht.Cells[6, 4] = ComputerTxt.Text;
xlsht.Cells[6, 5] = BarcodeTxt.Text;
xlsht.SaveAs(#"D:\" + ComputerTxt.Text + ".xlsx");
xlApp.Visible = true;
}
catch (Exception)
{
MessageBox.Show("Error Occured Cannot Save Sheet 2");
}
}
despite documentation, Worksheet.SaveAs() would lead to an error, so you have to use Workbook.SaveAs()
You're also opening two different Excel instances where you need only one and apparently leaving both them running!
Finally, you'd better open an Excel instance for all operations and hence distributing necessary code at Form class level (declarations), button1_Click() level (Excel and Workbook initialization), helper methods (Worksheet initializations)
As follows:
using System;
using System.Windows.Forms;
using Worksheet = Microsoft.Office.Interop.Excel.Worksheet;
using Workbook = Microsoft.Office.Interop.Excel.Workbook;
using MsExcelApp = Microsoft.Office.Interop.Excel.Application;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
MsExcelApp xlApp =;
Workbook xlWb;
Worksheet xlSht;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"D:\test.xlsx";
xlApp = new MsExcelApp();
try
{
xlWb = xlApp.Application.Workbooks.Open(path);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
PM_Sheet1();
PM_Sheet2();
try
{
xlWb.SaveAs(#"D:\" + ComputerTxt.Text + ".xlsx");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
xlApp.Quit();
}
protected void PM_Sheet1()
{
try
{
xlSht = xlWb.Worksheets["PM"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
xlSht.Cells[11, 2] = UserNameTxt.Text + "#rasatop.com";
xlSht.Cells[11, 4] = UserNameTxt.Text;
xlSht.Cells[14, 2] = SerialTxt.Text;
xlSht.Cells[16, 2] = WLANMacTxt.Text;
xlSht.Cells[16, 3] = LANMacTxt.Text;
xlSht.Cells[16, 4] = IPTxt.Text;
xlSht.Cells[14, 5] = ComputerTxt.Text;
xlSht.Cells[16, 5] = BarcodeTxt.Text;
xlSht.Cells[18, 5] = CPUTxt.Text.Substring(0, 26);
xlsht.Cells[18, 4] = VGATxt.Text;
xlsht.Cells[18, 3] = RAMTxt.Text;
xlsht.Cells[27, 4] = OSTxt.Text;
xlSht.Cells[5, 4] = System.DateTime.Today;
xlSht.Cells[26, 4] = System.DateTime.Today;
xlSht.Cells[9, 5] = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
}
protected void PM_Sheet2()
{
try
{
xlSht = xlWb.Worksheets["km"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
xlSht.Cells[4, 2] = System.DateTime.Today;
xlSht.Cells[6, 2] = UserNameTxt.Text;
xlSht.Cells[6, 4] = ComputerTxt.Text;
xlSht.Cells[6, 5] = BarcodeTxt.Text;
}
}
}

Add image from application to excel cells c#

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);
}

How to add column header to excel sheet?

private void btn_gnrt_files_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
//reading text file
FileInfo theSourceFile = new FileInfo(#"" + textBox1.Text);
StreamReader reader = theSourceFile.OpenText();
String filename = "";
String text = "";
do
{
text = reader.ReadLine();
if (text != null)
{
//MessageBox.Show(""+state);
String[] fname = text.Split('|'); //writiting file
if (state == true)
{
filename = fname[1];
filename.TrimStart();
//MessageBox.Show(filename);
Excel.Application excel = new Excel.Application();
excel.Visible = true;
//true is append parameter
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
writer.WriteLine(text.Replace("|", ","));
I get excel files with data through this code. but i cant
put column headers to excel sheets. plz tell me how to add these headers
<<reg no,br no,pr no,curency>>
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
System.Windows.MessageBox.Show("Excel is not properly installed!!");
return;
}
xlWorkBook = xlApp.Workbooks.Add();
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "reg no";
xlWorkSheet.Cells[1, 2] = "br no"
xlWorkSheet.Cells[1, 3] = "pr no"
xlWorkSheet.Cells[1, 4] = "curency";
And then do your business...
Column headers are just regular cells in Excel (or CSV), so add them as a first line.
Add that header-line before you start the loop to write the data lines.

How to make the header font bold while exporting dataset to excel?

Here i am exporting the datatables in a dataset to excel.How to make the header font of the datatable alone look bold.Here is my code
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid dataExportExcel = new DataGrid();
foreach (DataTable table in dtInputParameters.Tables)
{
dataExportExcel.DataSource = table;
dataExportExcel.DataBind();
dataExportExcel.RenderControl(htmlWrite);
htmlWrite.WriteLine("<br/>");
// htmlWrite.AddStyleAttribute(System.Web.UI.HtmlTextWriterStyle.FontWeight, "bold");
}
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + worksheetName + "</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head> <body>");
sbResponseString.Append(stringWriter + "<table width='800' height='100' align='center' style='text-align:center'");
sbResponseString.Append("</table></body></html>");
HttpContext.Current.Response.Write(sbResponseString.ToString());
HttpContext.Current.Response.End();
Any suggestion?
You need to set the HeaderStyle on the DataGrid to use bold font. That's all.
dataExportExcel.HeaderStyle.Font.Bold=true;
Cursor.Current = Cursors.WaitCursor;
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "Total Expiry Inventories Data ";
sfd.DefaultExt = "xls";
sfd.Filter = "xlsx files(*.xlsx)|*.xlsx";
if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook workbook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet1 = (Excel.Worksheet)workbook.Worksheets[1];
worksheet1.Name = "Expiry Data";
for (int i = 1; i < GrdViewData.Columns.Count + 1; i++)
{
worksheet1.Cells[1, i] = GrdViewData.Columns[i - 1].HeaderText;
worksheet1.Cells[1, i].Font.Bold = true;
}
for (int i = 0; i < GrdViewData.Rows.Count; i++)
{
for (int j = 0; j < GrdViewData.Columns.Count; j++)
{
worksheet1.Cells[i + 2, j + 1] = GrdViewData.Rows[i].Cells[j].Value.ToString();
}
}
worksheet1.Rows.Font.Size = 12;
// Excel.Range range_Consolidated = worksheet1.Rows.get_Range("a1", "d1");
// range_Consolidated.Font.Bold = true;
// range_Consolidated.Font.Italic = true;
string ExcelFileName = sfd.FileName;
workbook.SaveAs(ExcelFileName);
workbook.Close(false, ExcelFileName, Missing.Value);
ExcelApp.Quit();
ExcelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show("File Saved! you can open it from\n '" + sfd.FileName + "'", "EXPORT", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}

Categories