C#下 将ListView 导出到Excel 改进了09年的那个datatable 导出的功能
首先 你需要添加引用Microsoft Excel 11.0 Object Library
添加方法:选择项目->引用->右击“添加引用”->选择COM 找到上面组件—>点击“确定”。
然后使用跟09年我写的那个导出方法差不多的一个方法代码:
//界面添加一个导出的Button
private void m_btnExport_Click(object sender, EventArgs e)
{
m_mthExportToExecl();
}
//执行导出
public void m_mthExportToExecl()
{
this.m_objSave.DefaultExt = "xls";
this.m_objSave.Filter = "Excel文件(*.xls)|*.xls";
if (this.m_objSave.ShowDialog() == DialogResult.OK)
{
m_mthDoExport(this.m_lvResult, m_objSave.FileName);
}
}
//具体导出的方法
private void m_mthDoExport(ListView dtSource, string strFileName)
{
int rowNum = dtSource.Items.Count;
int columnNum = dtSource.Items[0].SubItems.Count;
int rowIndex = 1;
int columnIndex = 0;
if (rowNum == 0 || string.IsNullOrEmpty(strFileName))
{
return;
}
if (rowNum > 0)
{
Excel.Application xlApp = new Excel.ApplicationClass();
if (xlApp == null)
{
MessageBox.Show("无法创建excel对象,可能您的系统没有安装excel");
return;
}
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//将ListView的列名导入Excel表第一行
foreach (ColumnHeader dc in dtSource.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(dtSource.Items[i].SubItems[j].Text)+"\t";
}
}
// 这里原来用的是SaveCopyAs 的方法 这个方法的一个问题就是报存的Excel文档多了一个Sheet.用下面这个方面可以避免这个问题。
//例外需要说明的是用strFileName,Excel.XlFileFormat.xlExcel9795保存方式时 当你的Excel版本不是95、97 而是2003、2007 时导出的时候会报一个错误:
// 异常来自 HRESULT:0x800A03EC。 解决办法就是换成strFileName,Excel.XlFileFormat.xlWorkbookNormal。
xlBook.SaveAs(strFileName,Excel.XlFileFormat.xlWorkbookNormal,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlSaveAsAccessMode.xlExclusive,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);// (strFileName);
xlApp = null;
xlBook = null;
}
}