简体   繁体   中英

Add text to row 1 in excel export listview

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM