c#winform导出到excel,office2016_保存退出
引用:
OFFICE.DLL
Microsoft.Office.Interop.Excel.dll
public static void ToExcel(ListView LView, string strTitle) { try { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); object m_objOpt = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Workbooks ExcelBooks = (Microsoft.Office.Interop.Excel.Workbooks)ExcelApp.Workbooks; Microsoft.Office.Interop.Excel._Workbook ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)(ExcelBooks.Add(m_objOpt)); Microsoft.Office.Interop.Excel._Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet; //设置标题 ExcelApp.Caption = strTitle; ExcelSheet.Cells[1, 1] = strTitle; //写入内容 for (int i = 3; i < LView.Items.Count + 3; i++) { ExcelSheet.Cells[i + 2, 1] = LView.Items[i - 3].Text; // ExcelSheet.Cells[2, i - 2] = LView.Items[i - 3].SubItems[0].Text;//机台 //ExcelSheet.Cells[3, i - 2] = LView.Items[i - 3].SubItems[4].Text;//产出 for (int j = 1; j <= LView.Columns.Count; j++) { ExcelSheet.Cells[i + 2, j] = LView.Items[i - 3].SubItems[j - 1].Text; } } //显示Excel ExcelApp.Visible = true; } catch (SystemException e) { MessageBox.Show(e.ToString()); } } private void button_export_excel_Click(object sender, EventArgs e) { ToExcel(listView_data_base, "AGV运单记录"); } }
打开指定excel文件,保存,与退出。
private void testExcel(ListView LView, string strTitle) { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); ExcelApp.Visible = true; object m_objOpt = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Workbooks ExcelBooks = (Microsoft.Office.Interop.Excel.Workbooks)ExcelApp.Workbooks; Microsoft.Office.Interop.Excel._Workbook ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)(ExcelBooks.Open(@"D:\test11.xlsx")); Microsoft.Office.Interop.Excel._Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet; ExcelSheet.Cells[1, 1] = "tt1"; ExcelBook.Save(); // ExcelBook.Close(); ExcelApp.Quit(); }
欢迎讨论,相互学习。
cdtxw@foxmail.com