2017-07-26 91 views
-3

我有5個列表視圖,我想將它們導出到一個CSV文件中。將列表視圖的內容導出到CSV文件

This is my 5 listview

在ListView,你可以看到,日期時間是所有6名列表視圖相同。

所以我能夠將第一個listview導出到一個CSV文件。

 saveFileDialog1.Filter = "csv files (*.csv)|*.csv"; 
     saveFileDialog1.FileName = "logs"; 
     saveFileDialog1.Title = "Export to Excel"; 
     StringBuilder sb = new StringBuilder(); 
     foreach (ColumnHeader ch in listView1.Columns) 
     { 
      sb.Append(ch.Text + ","); 
     } 
     sb.AppendLine(); 
     foreach (ListViewItem lvi in listView1.Items) 
     { 
      foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems) 
      { 
       if (lvs.Text.Trim() == string.Empty) 
        sb.Append(" ,"); 
       else 
        sb.Append(lvs.Text + ","); 
      } 
      sb.AppendLine(); 
     } 
     DialogResult dr = saveFileDialog1.ShowDialog(); 
     if (dr == DialogResult.OK) 
     { 
      StreamWriter sw = new StreamWriter(saveFileDialog1.FileName); 
      sw.Write(sb.ToString()); 
      sw.Close(); 

      this.Close(); 
     } 

現在我想剩下的其他4列表視圖導出到同一個CSV文件,其中第一colomn將日期時間,這是所有5列表視圖相同。

我該如何去做?

回答

0

完整的代碼來完成你的任務

class ListViewToCSV 
{ 
    public static void ListViewToCSV(ListView listView, string filePath, bool includeHidden) 
    { 
     //make header string 
     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 (ListViewItem 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 static 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(); 
    } 
}