C#如何将ListView中的数据导出到Excel中
首先,我们需要添加引用。选择Microsof Excel xx.0 Object Library,不同电脑的COM可能不一样,这里用xx表示可能的数字。
添加方法:项目中的引用->右击选择“添加引用”->选择COM,找到上面的组件->点击“确定”。
下面是简要的代码:
- // 添加命名空间
- using Excel = Microsoft.Office.Interop.Excel;
- // 定义全局变量
- Excel.Application App = new Excel.Application();
- Excel.Workbook wb;
- Excel._Worksheet ws;
- object misValue = System.Reflection.Missing.Value;
- // 自定义创建新excel文件的函数
- public bool createNewFile(string newFileName)
- {
- if (app == null)
- {
- MessageBox.Show("无法创建excel对象,请检查您的系统是否安装了excel。");
- return false;
- }
- App.DisplayAlerts = true;
- App.Visible = false; // invisible
- wb = App.Workbooks.Open(newFileName, misValue, true, misValue,
- misValue, misValue, misValue, misValue,
- misValue, true, misValue, misValue, misValue, misValue, misValue);
- return true;
- }
- // 保存excel文件
- public void saveFile(string newFileName)
- {
- wb.SaveAs(newFileName, Excel.XlFileFormat.xlWorkbookNormal, misValue,
- misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive,
- misValue, misValue, misValue, misValue, misValue);
- wb.Close(true, misValue, misValue);
- App.DisplayAlerts = false;
- App.AlertBeforeOverwriting = false;
- App.Quit();
- MessageBox.Show("文件已经生成。");
- //System.Diagnostics.Process.Start("E:\\");
- }
- // 按照一格一格写入的方式自定义函数
- public void writeCell(string sheet, int row, int col, string cont)
- {
- ws = wb.Sheets[sheet];
- ws.Activate();
- ws.Cells[row, col] = cont;
- }
- private void exportListViewData(ListView lstView, string tempFileName, string finalFileName)
- {
- int nRow =lstView.Items.Count;
- int nCol = lstView.Columns.Count;
- if (nRow == 0)
- {
- MessageBox.Show("保存错误,没有任何数据。");
- return;
- }
- createNewFile(tempFileName);
- for (int i = 0; i < nRow; i++)
- {
- for (int j = 0; j < nCol; j++)
- {
- writeCell("sheet1", i + 3, j + 2, lstView.Items[i].SubItems[j].Text.ToString()); // 默认sheet1工作表,可以修改
- }
- }
- saveFile(finalFileName);
- }