C#中將ListView中資料匯出到Excel的執行個體方法

來源:互聯網
上載者:User

添加方法:選擇項目->引用->右擊“添加引用”->選擇COM 找到上面組件—>點擊“確定”。
實現代碼如下:

複製代碼 代碼如下: private void 匯出資料_Click(object sender, EventArgs e)
{
ExportToExecl();
}
/// <summary>
/// 執行匯出資料
/// </summary>
public void ExportToExecl()
{
System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "xls";
sfd.Filter = "Excel檔案(*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
DoExport(this.lstPostion, sfd.FileName);
}
}
/// <summary>
/// 具體匯出的方法
/// </summary>
/// <param name="listView">ListView</param>
/// <param name="strFileName">匯出到的檔案名稱</param>
private void DoExport(ListView listView, string strFileName)
{
int rowNum = listView.Items.Count;
int columnNum = listView.Items[0].SubItems.Count;
int rowIndex = 1;
int columnIndex = 0;
if (rowNum == 0 || string.IsNullOrEmpty(strFileName))
{
return;
}
if (rowNum > 0)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
MessageBox.Show("無法建立excel對象,可能您的系統沒有安裝excel");
return;
}
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//將ListView的列名匯入Excel表第一行
foreach (ColumnHeader dc in listView.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.Text;
}
//將ListView中的資料匯入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
//注意這個在匯出的時候加了“\t” 的目的就是避免匯出的資料顯示為科學計數法。可以放在每行的首尾。
xlApp.Cells[rowIndex, columnIndex] = Convert.ToString(listView.Items[i].SubItems[j].Text) + "\t";
}
}
//例外需要說明的是用strFileName,Excel.XlFileFormat.xlExcel9795儲存方式時 當你的Excel版本不是95、97 而是2003、2007 時匯出的時候會報一個錯誤:異常來自 HRESULT:0x800A03EC。 解決辦法就是換成strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal。
xlBook.SaveAs(strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlApp = null;
xlBook = null;
MessageBox.Show("OK");
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.