使用较少的列复制列表视图

时间:2011-11-03 10:34:52

标签: c# asp.net excel listview

我的asp页面上有一个listview,我需要将它导出到excel代码后面(c#)。但是我不希望导出所有列。

是否可以将ListView复制到具有较少列的新ListView对象中? 或者是否有另一种方法可以将列表视图导出到excel中的列数更少?

这就是我在代码中将代码导出到excel的方式:

protected void ExportToExcel(object sender, EventArgs e)
{   
    string attachment = "attachment; filename=MyData.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    Response.ContentEncoding = Encoding.Unicode;
    Response.BinaryWrite(Encoding.Unicode.GetPreamble());
    StringWriter stw = new StringWriter();
    HtmlTextWriter htextw = new HtmlTextWriter(stw);                
    // How can I render myListView with fewer columns?
    myListView.RenderControl(htextw);
    Response.Write(stw.ToString());
    Response.End();
}

提前致谢,

1 个答案:

答案 0 :(得分:1)

class ListViewToCSV
{
    public static void ListViewToCSV(ListView listView, string filePath, bool includeHidden)
    {
        //make header srting
        StringBuilder result = new StringBuilder();
        WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listView.Columns[i].Text);

        //export data rows
        foreach (var listItem in listView.Items)
            WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listItem.SubItems[i].Text);

        File.WriteAllText(filePath, result.ToString());
    }

    private void WriteCSVRow(StringBuilder result, int itemsCount, Func<int, bool> isColumnNeeded, Func<int, string> columnValue)
    {
        bool isFirstTime = true;
        for (int i = 0; i < itemsCount; i++)
        {
            if (!isColumnNeeded(i))
                continue;

            if (!isFirstTime)
                result.Append(",");
            isFirstTime = false;

            result.Append(String.Format("\"{0}\"", columnValue(i)));
        }
        result.AppendLine();
    }
}