文档库 最新最全的文档下载
当前位置:文档库 › VC操作Excel

VC操作Excel

1. //需在工程中增加相应的excel.h和excel.cpp
2. //vc 删除excel中的一行
3. //////////////////////////////////////////////////////////////////////////
4. try
5. {
6. _Application app; // app is an _Application object.
7. _Workbook book; // More object declarations.
8. _Worksheet sheet;
9. Workbooks books;
10. Worksheets sheets;
11. Range range; // Used for Microsoft Excel 97 components.
12. LPDISPATCH lpDisp; // Often reused variable.
13. COleVariant
14. covTrue((short)TRUE),
15. covFalse((short)FALSE),
16. covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
17. if(!app.CreateDispatch("Excel.Application"))
18. {
19. AfxMessageBox("Couldn't CreateDispatch() for Excel");
20. // return; //huxianbiao delete
21. }
22. app.SetVisible(TRUE);
23. lpDisp = app.GetWorkbooks(); // Get an IDispatch pointer.
24. ASSERT(lpDisp);
25. books.AttachDispatch(lpDisp); // Attach the IDispatch pointer
26. // to the books object.
27. lpDisp = books.Open(csExcelName/*"D:\\Onega\\Book2.xls"*/, // Test.xls is a workbook.
28. covOptional, covOptional, covOptional, covOptional, covOptional,
29. covOptional, covOptional, covOptional, covOptional, covOptional,
30. covOptional, covOptional, covOptional, covOptional ); // Return Workbook's IDispatch
31. // pointer.
32. book.AttachDispatch( lpDisp );
33. lpDisp = book.GetSheets();
34. ASSERT(lpDisp);
35. sheets.AttachDispatch(lpDisp);
36. lpDisp = sheets.GetItem( COleVariant((short)(1)) );
37. ASSERT(lpDisp);
38. sheet.AttachDispatch(lpDisp);
39. // Delete Row of A13, Onega(https://www.wendangku.net/doc/3d7425121.html,)
40. // VC6.0 SP6, Excel2003
41. lpDisp = sheet.GetRange(COleVariant("A1"), COleVariant("A1"));
42. range.AttachDispatch(lpDisp);
43. lpDisp = range.GetEntireRow();
44. Range entire_row;
45. entire_row.AttachDispatch(lpDisp);
46. long xlUp = -4162;
47. entire_row.Delete(COleVariant(xlUp)); //删除excel中的一行
48. book.Save();
49. app.Quit();
50. } // End of processing.
51.
52. catch(COleException *e)
53. {
54. char buf[1024]; // For the Try...Catch error message.
55. sprintf(buf, "COleException. SCODE: %08lx.", (long)e->m_sc);
56. ::MessageBox(NULL, buf, "COleException", MB_SETFOREGROUND | MB_OK);
57. }
58. catch(COleDispatchException *e)
59. {
60. char buf[1024]; // For the Try...Catch error message.


61. sprintf(buf,
62. "COleDispatchException. SCODE: %08lx, Description: \"%s\".",
63. (long)e->m_wCode,(LPSTR)e->m_strDescription.GetBuffer(512));
64. ::MessageBox(NULL, buf, "COleDispatchException",
65. MB_SETFOREGROUND | MB_OK);
66. }
67. catch(...)
68. {
69. ::MessageBox(NULL, "General Exception caught.", "Catch-All",
70. MB_SETFOREGROUND | MB_OK);
71. }

相关文档