利用vc的mfc做的Excel表格处理工具
生活随笔
收集整理的這篇文章主要介紹了
利用vc的mfc做的Excel表格处理工具
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
下面兩個文件是邏輯處理文件。已經(jīng)調(diào)通。
CExcelmadetoolDlg.h
在這里插入代碼片 // ExcelmadetoolDlg.h : header file //#if !defined(AFX_EXCELMADETOOLDLG_H__9A8C90C3_A3D6_4DCB_BC96_4F62C05EEE78__INCLUDED_) #define AFX_EXCELMADETOOLDLG_H__9A8C90C3_A3D6_4DCB_BC96_4F62C05EEE78__INCLUDED_#if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000/ // CExcelmadetoolDlg dialog #include "tlhelp32.h" //頭文件 class CExcelmadetoolDlg : public CDialog { // Construction public:CExcelmadetoolDlg(CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CExcelmadetoolDlg)enum { IDD = IDD_EXCELMADETOOL_DIALOG };// NOTE: the ClassWizard will add data members here//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CExcelmadetoolDlg)int madeExcel();void GetEditworth();//獲取控件的值void GetSNAllworth();//獲取sn總共的值long chToLong(const char *ch,int len);//用于處理填入序列號的數(shù)據(jù)void StrtoInt(CString *const putStr,int *const putInt);//字符串轉(zhuǎn)換為int,不能改變指針地址CString strSNAllPath;//用于添加SN表單的路徑CString strADDRPath;//用于添加地址表單的路徑int startLine;//起始行int EndLine;//終止行CString StartSN;//起始SN序列號CString CSLogistics;//物流公司CString CSLogisticsNumber;//物流單號int IClientSnNum;//客戶SN序列號總數(shù)CString SheetName;//表單名字int impliedSNAllLine;//默認打印總的表格數(shù)字protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//EDIT控件CEdit* pBoxStart;CEdit* pBoxEnd;//}}AFX_VIRTUAL// Implementation protected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CExcelmadetoolDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnOk2();afx_msg void Onaddr();virtual void OnOK();//}}AFX_MSGDECLARE_MESSAGE_MAP() };//{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif // !defined(AFX_EXCELMADETOOLDLG_H__9A8C90C3_A3D6_4DCB_BC96_4F62C05EEE78__INCLUDED_)CExcelmadetoolDlg.cpp
在這里插入代碼片 // ExcelmadetoolDlg.cpp : implementation file //#include "stdafx.h" #include "Excelmadetool.h" #include "ExcelmadetoolDlg.h" #include <comdef.h> #include "excel.h" #include <shlwapi.h> #include <sstream> #include <string> #include <iostream> #include <stdlib.h> #include <math.h> #include <limits.h> #include <windows.h>#pragma comment(lib,"shlwapi.lib") //如果沒有這行,會出現(xiàn)link錯誤 //#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif//要操作表,必須先逐步獲取Workbooks->Workbook->Worksheets->Worksheet->Range //并設(shè)置全局變量 _Application g_app; Workbooks g_books; _Workbook g_book; Sheets g_sheets; //低版本Office請將這改為 WorkSheets _Worksheet g_sheet; Range g_range; Font font; int SNnum=0;/ // CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialog { public:CAboutDlg();// Dialog Data//{{AFX_DATA(CAboutDlg)enum { IDD = IDD_ABOUTBOX };//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAboutDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//}}AFX_VIRTUAL// Implementation protected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_MESSAGE_MAP() };CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) {//{{AFX_DATA_INIT(CAboutDlg)//}}AFX_DATA_INIT }void CAboutDlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAboutDlg)//}}AFX_DATA_MAP }BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)// No message handlers//}}AFX_MSG_MAP END_MESSAGE_MAP()/ // CExcelmadetoolDlg dialogCExcelmadetoolDlg::CExcelmadetoolDlg(CWnd* pParent /*=NULL*/): CDialog(CExcelmadetoolDlg::IDD, pParent) {//{{AFX_DATA_INIT(CExcelmadetoolDlg)// NOTE: the ClassWizard will add member initialization here//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); }void CExcelmadetoolDlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CExcelmadetoolDlg)// NOTE: the ClassWizard will add DDX and DDV calls here//}}AFX_DATA_MAP }BEGIN_MESSAGE_MAP(CExcelmadetoolDlg, CDialog)//{{AFX_MSG_MAP(CExcelmadetoolDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDOK2, OnOk2)ON_BN_CLICKED(IDOK3, Onaddr)//}}AFX_MSG_MAP END_MESSAGE_MAP()/ // CExcelmadetoolDlg message handlersBOOL CExcelmadetoolDlg::OnInitDialog() {CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically// when the application's main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization here//綁定控件pBoxStart = (CEdit*) GetDlgItem(IDC_EDIT1);pBoxEnd = (CEdit*) GetDlgItem(IDC_EDIT2);//初始化startLine=0;EndLine=0;//給定控件默認值pBoxStart-> SetWindowText( "2" );pBoxEnd-> SetWindowText( "2" );AfxOleInit();if(!g_app.CreateDispatch("Excel.Application")){AfxMessageBox("無法啟動Excel服務(wù)器");return;}SetWindowText("Excel表格處理工具");return TRUE; // return TRUE unless you set the focus to a control }void CExcelmadetoolDlg::OnSysCommand(UINT nID, LPARAM lParam) {if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);} }// If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework.void CExcelmadetoolDlg::OnPaint() {if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();} }// The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CExcelmadetoolDlg::OnQueryDragIcon() {return (HCURSOR) m_hIcon; }void CExcelmadetoolDlg::OnOk2() {// TODO: Add your control notification handler code hereCOleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR); CFileDialog dlg(true,"配置文件",NULL,0, "表格文件(.xls)|*.xls|表格文件(.xlsx)|*.xlsx");//打開文件if(IDOK==dlg.DoModal())strSNAllPath =dlg.GetPathName();//沒有添加提示,工作簿創(chuàng)建 // if(!g_app.CreateDispatch("Excel.Application")) // { // AfxMessageBox("無法啟動Excel服務(wù)器"); // return; // }//利用模板文件建立新文檔 g_books.AttachDispatch(g_app.GetWorkbooks(),true); g_book.AttachDispatch(g_books.Add(_variant_t(strSNAllPath)),true);// //獲取所有的工作簿 // g_books = g_app.GetWorkbooks(); // // //用來鎖定對應(yīng)的工作簿 // g_books.AttachDispatch(g_app.GetWorkbooks(),true); // g_book = g_books.Open( strSNAllPath,covOptional,covOptional, // covOptional,covOptional,covOptional,covOptional, // covOptional,covOptional,covOptional,covOptional, // covOptional,covOptional,covOptional,covOptional);//得到Worksheets,工作表g_sheets.AttachDispatch(g_book.GetWorksheets(),true);g_sheet=g_sheets.GetItem(COleVariant((short)1));//獲得使用的區(qū)域g_range.AttachDispatch(g_sheet.GetUsedRange(),true);//獲取使用的行數(shù)int usedrowNum=0;g_range.AttachDispatch(g_range.GetRows(),true);usedrowNum=g_range.GetCount();//獲取使用的列數(shù)int usedrowCol=0;g_range.AttachDispatch(g_range.GetColumns(),true);usedrowCol=g_range.GetCount();//獲取第一行第一列的值COleVariant vResult;g_range.AttachDispatch(g_sheet.GetCells());g_range.AttachDispatch(g_range.GetItem(COleVariant((long)2), COleVariant((long)1)).pdispVal);//行與列vResult = g_range.GetValue2();//獲取工作表的名字CString sheetName=g_sheet.GetName();//展現(xiàn)文檔 // g_app.SetVisible(true); //釋放對象 g_books.Close();g_app.Quit(); g_range.ReleaseDispatch(); g_sheet.ReleaseDispatch(); g_sheets.ReleaseDispatch(); g_book.ReleaseDispatch(); g_books.ReleaseDispatch(); g_app.ReleaseDispatch(); }void CExcelmadetoolDlg::OnOK() {// TODO: Add extra validation here//_Application g_Newapp; //Workbooks g_Newbooks; //_Workbook g_Newbook; //Sheets g_Newsheets; //低版本Office請將這改為 WorkSheets //_Worksheet g_Newsheet; //Range g_Newrange; //Font Newfont;//GetEditworth();//獲取EDIT控件的值if( FAILED( CoInitialize(NULL) ) ) { AfxMessageBox("初始化COM支持庫失敗!"); }//利用模板文件建立新文檔 //g_Newbooks.AttachDispatch(g_Newapp.GetWorkbooks(),true); // g_Newbook.AttachDispatch(g_Newbooks.Add(_variant_t(strADDRPath)),true); // //得到Worksheets //g_Newsheets.AttachDispatch(g_Newbook.GetWorksheets(),true); //得到sheet1 //g_Newsheet.AttachDispatch(g_Newsheets.GetItem(_variant_t("sheet1")),true); //得到全部Cells,此時,g_range是cells的集合 //g_Newrange.AttachDispatch(g_Newsheet.GetCells(),true); //設(shè)置1行1列的單元的值 //g_Newrange.SetItem(_variant_t((long)1),_variant_t((long)1),_variant_t("This Is A Excel Test Program!")); //得到所有的列 //g_Newrange.AttachDispatch(g_Newsheet.GetColumns(),true); //得到第一列 //g_Newrange.AttachDispatch(g_Newrange.GetItem(_variant_t((long)1),vtMissing).pdispVal,true); //設(shè)置列寬 //g_Newrange.SetColumnWidth(_variant_t((long)20)); //Range cols; //cols = g_Newrange.GetEntireColumn();//選擇整列,并設(shè)置寬度為自適應(yīng) //cols.AutoFit(); //調(diào)用模板中預(yù)先存放的宏 //g_app.Run(_variant_t("CopyRow"),_variant_t((long)10), _variant_t(vtMissing),_variant_t(vtMissing), //_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing), //_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing), //_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing), //_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing),_variant_t(vtMissing)); //制作表格 //font=g_range.GetFont(); // g_range=g_sheet.GetRange(COleVariant("A2"),COleVariant("A2")); //g_range.SetFormula(COleVariant("=RAND()*100000")); //g_range.SetNumberFormat(COleVariant("$0.00")); //制作表格內(nèi)容//填寫標題. // g_range = g_sheet.GetRange(COleVariant("A1"),COleVariant("A1")); // g_range.SetNumberFormatLocal(COleVariant("列1")); // g_range = g_sheet.GetRange(COleVariant("B1"),COleVariant("B1")); // g_range.SetNumberFormatLocal(COleVariant("列2")); // g_range = g_sheet.GetRange(COleVariant("C1"),COleVariant("C1")); // g_range.SetNumberFormatLocal(COleVariant("列3")); // g_range = g_sheet.GetRange(COleVariant("D1"),COleVariant("D1")); // g_range.SetNumberFormatLocal(COleVariant("列4")); // g_range = g_sheet.GetRange(COleVariant("E1"),COleVariant("E1")); // g_range.SetNumberFormatLocal(COleVariant("列5"));// g_Newrange.SetItem(_variant_t((long)1),_variant_t((long)1),_variant_t("SN序列號")); // g_Newrange.SetItem(_variant_t((long)1),_variant_t((long)2),_variant_t("物流單號"));////獲取所有的工作簿COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR); if(!g_app.CreateDispatch("Excel.Application")){AfxMessageBox("無法啟動Excel服務(wù)器");return;}//為了防止用戶多點MessageBox("正在寫入,請稍后!");g_books = g_app.GetWorkbooks(); //用來鎖定對應(yīng)的工作簿 g_books.AttachDispatch(g_app.GetWorkbooks(),true); g_book.AttachDispatch(g_books.Add(_variant_t(strADDRPath)),true);/*g_book = g_books.Open( strADDRPath,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional);*///得到Worksheets,工作表g_sheets.AttachDispatch(g_book.GetWorksheets(),true);g_sheet=g_sheets.GetItem(COleVariant((short)1));//獲得使用的區(qū)域g_range.AttachDispatch(g_sheet.GetUsedRange(),true);//獲取使用的行數(shù)int usedrowNum=0;g_range.AttachDispatch(g_range.GetRows(),true);usedrowNum=g_range.GetCount(); //獲取使用的列數(shù)int usedrowCol=0;g_range.AttachDispatch(g_range.GetColumns(),true);usedrowCol=g_range.GetCount();//獲取收貨公司表單//獲取第2行第6列的值GetEditworth();//函數(shù)出現(xiàn)問題//取值 // CString strStart; // CString strEnd; // // pBoxStart-> GetWindowText(strStart); // pBoxEnd-> GetWindowText(strEnd);// startLine= atoi( LPCTSTR(strStart) ); // EndLine= atoi( LPCTSTR(strEnd) );for(int i=startLine;i<EndLine+1;i++){//獲取第I行表單總數(shù)// COleVariant vResultSNALL; // g_range.AttachDispatch(g_sheet.GetCells()); // g_range.AttachDispatch(g_range.GetItem(COleVariant((long)i), COleVariant((long)6)).pdispVal);//行與列 // vResultSNALL = g_range.GetValue2();_variant_t var;CString tmpStr;//存儲每個格子的數(shù)據(jù)g_range.AttachDispatch(g_sheet.GetCells());var =g_range.GetItem(_variant_t((long)i),_variant_t((long)7));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始tmpStr.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CStringStrtoInt(&tmpStr,&IClientSnNum);//CString CSnAll;//CSnAll.Format("%f", vResultSNALL.dblVal); //SN起始數(shù)var =g_range.GetItem(_variant_t((long)i),_variant_t((long)8));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始StartSN.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CString//物流公司名字var =g_range.GetItem(_variant_t((long)i),_variant_t((long)10));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始CSLogistics.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CString//物流單號var =g_range.GetItem(_variant_t((long)i),_variant_t((long)11));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始CSLogisticsNumber.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CString// COleVariant vResultWuliu; // g_range.AttachDispatch(g_range.GetItem(COleVariant((long)i), COleVariant((long)9)).pdispVal);//行與列 // vResultWuliu = g_range.GetValue2(); // CSLogistics=(BSTR)vResultWuliu.pbstrVal;//CSLogistics.Format("%f", vResultWuliu.dblVal); //給定表單名字CString strCOmpany;CString strPeopleName;//獲取收貨公司序號CString CNumberComper;var =g_range.GetItem(_variant_t((long)i),_variant_t((long)3));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始CNumberComper.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CString//獲取公司名字var =g_range.GetItem(_variant_t((long)i),_variant_t((long)4));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始strCOmpany.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CString// COleVariant vResultGetcompany; // g_range.AttachDispatch(g_range.GetItem(COleVariant((long)i), COleVariant((long)3)).pdispVal);//行與列 // vResultGetcompany = g_range.GetValue2(); // strCOmpany=(BSTR)vResultGetcompany.pbstrVal;//strCOmpany.Format("%f", vResultGetcompany.dblVal); //獲取人名var =g_range.GetItem(_variant_t((long)i),_variant_t((long)4));//讀取第r行c列的數(shù)據(jù),注意行和列都是從1開始strPeopleName.Format("%s",(char*)(_bstr_t)var);//轉(zhuǎn)換成CString//除掉人名后面的電話號碼//rPeopleName = strPeopleName.substr(0, strPeopleName.length() - 11);//rPeopleName.erase(strPeopleName.end() - 1);// COleVariant vResultGetPeopleName; // g_range.AttachDispatch(g_range.GetItem(COleVariant((long)i), COleVariant((long)4)).pdispVal);//行與列 // vResultGetPeopleName = g_range.GetValue2(); // strPeopleName=(BSTR)vResultGetcompany.pbstrVal;// strPeopleName.Format("%f", vResultGetPeopleName.dblVal); //表單名字SheetName=CNumberComper+strCOmpany+strPeopleName;madeExcel();}//導(dǎo)入數(shù)據(jù). // putlonth=Modeworth.GetLength(); // putWorth=Modeworth.Right(putlonth-3); // //總行數(shù) // int AllrowsWorth=100;//madeExcel() ; //int m,n; //int rows=50; //打印預(yù)覽 g_book.SetSaved(true); g_app.SetVisible(true); // //g_book.PrintPreview(_variant_t(false)); //釋放對象 g_books.Close();g_app.Quit(); g_range.ReleaseDispatch(); g_sheet.ReleaseDispatch(); g_sheets.ReleaseDispatch(); g_book.ReleaseDispatch(); g_books.ReleaseDispatch(); g_app.ReleaseDispatch(); // MessageBox("生產(chǎn)表單完畢!!"); CDialog::OnOK(); }//創(chuàng)建表格 int CExcelmadetoolDlg::madeExcel() {_Application g_Newapp; Workbooks g_Newbooks; _Workbook g_Newbook; Sheets g_Newsheets; //低版本Office請將這改為 WorkSheets _Worksheet g_Newsheet; Range g_Newrange; Font Newfont;if( FAILED( CoInitialize(NULL) ) ) {AfxMessageBox("初始化COM支持庫失敗!"); } //AfxOleInit();//會引起中斷 // //導(dǎo)出//g_app.ReleaseDispatch(); COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR); if(!g_Newapp.CreateDispatch("Excel.Application")) {MessageBox("無法創(chuàng)建Excel應(yīng)用!");// exit(1); } //利用模板文件建立新文檔 g_Newbooks.AttachDispatch(g_Newapp.GetWorkbooks(),true); //g_Newbook.AttachDispatch(g_Newbooks.Add(_variant_t(strADDRPath)),true); g_Newbook=g_Newbooks.Add(covOptional); //得到Worksheets g_Newsheets.AttachDispatch(g_Newbook.GetWorksheets(),true); //得到sheet1 //g_Newsheet.AttachDispatch(g_Newsheets.GetItem(_variant_t("sheet1")),true); //得到第一個工作表 g_Newsheet=g_Newsheets.GetItem(COleVariant((short)1));//獲得使用的區(qū)域 //得到全部Cells,此時,g_range是cells的集合 g_Newrange.AttachDispatch(g_Newsheet.GetCells(),true); //設(shè)置1行1列的單元的值 //g_Newrange.SetItem(_variant_t((long)1),_variant_t((long)1),_variant_t("This Is A Excel Test Program!")); //得到所有的列 g_Newrange.AttachDispatch(g_Newsheet.GetColumns(),true); //得到第一列 //g_Newrange.AttachDispatch(g_Newrange.GetItem(_variant_t((long)1),vtMissing).pdispVal,true); //設(shè)置列寬 g_Newrange.SetColumnWidth(_variant_t((long)20)); Range cols; cols = g_Newrange.GetEntireColumn();//選擇整列,并設(shè)置寬度為自適應(yīng) cols.AutoFit(); cols.ReleaseDispatch(); bool TFvisible=false; g_Newapp.SetVisible(TFvisible); //不加文件刪不掉 g_Newapp.SetUserControl(TRUE);CString SaveFilePath=_T("D:\\SaveExcel");CString ExcelName=SheetName+".xlsx"; CString SaveExcelPath="D:\\SaveExcel\\"+ExcelName; if(!PathIsDirectory(SaveFilePath)) {//CreateDirectioy(SaveExcelPath,NULL);AfxMessageBox("存儲路徑不存在!請在D盤根目錄下建立SaveExcel文件夾,注意大小寫");exit(1); }//選擇工作表中A1:A1單元格區(qū)域g_Newrange=g_Newsheet.GetRange(COleVariant("A1"),COleVariant("A1")); g_Newrange.SetValue2(COleVariant("SN序列號")); //range.SetValue()必為range.SetValue2() //g_Newrange.SetFormulaR1C1( COleVariant("SN序列號") );//選擇工作表中A1:B1單元格區(qū)域g_Newrange=g_Newsheet.GetRange(COleVariant("B1"),COleVariant("B1")); g_Newrange.SetValue2(COleVariant("物流公司物流單號")); //range.SetValue()必為range.SetValue2()//將CString轉(zhuǎn)化為char數(shù)組char szTemp[30]="";memcpy(szTemp,StartSN,StartSN.GetLength()); //strcpy_s(szTemp, StartSN);int numIS0;//表示前面有多少0,最后添加//去掉char數(shù)組前面的0int snLonth=strlen(szTemp);for (int i=0;i<strlen(szTemp);i++) {if (szTemp[i]!='0'){ numIS0=i;break; //找出前面有幾個0}}strcpy(szTemp,szTemp+i); // 搬動字符串,版去掉領(lǐng)頭的零unsigned long a = 0;unsigned long b = 1;unsigned long sum = 0;for(i =strlen(szTemp)-1;i >= 0;i--){a= szTemp[i] - '0';a =a*b;sum += a;b = b*10;}int szTlong=strlen(szTemp);//CString CTempSNnumber;CTempSNnumber.Format("%s",szTemp); // char ch[]="123456789123456"; // unsigned __int64 LLsum=chToLong(ch,strlen(ch)); // unsigned __int64 mmmm=atoi(CTempSNnumber); // // // unsigned __int64 LStartSN;//= atol(a); // unsigned __int64 LongthSN= _ttol(CTempSNnumber);//unsigned __int64 UI64SNnumber=0;sscanf((LPSTR)(LPCTSTR)CTempSNnumber,"%I64d",&UI64SNnumber);//long filesize; //filesize=atol(m_FileSize.GetBuffer(m_FileSize.GetLength()));// char * pchar; // pchar=(LPSTR)(LPCSTR)StartSN;for(int j=2;j<IClientSnNum+2;j++ ){char c='0';CTempSNnumber.Format("%I64d",UI64SNnumber);for(int n=0;n<numIS0;n++){CTempSNnumber=c+CTempSNnumber;}CTempSNnumber="'"+CTempSNnumber;//StartSN=CTempSNnumber;// StartSN.Format(_T("%I64d"),IStartSN);//g_Newrange.SetItem(_variant_t((long)j),_variant_t((long)0),_variant_t(CTempSNnumber));// g_Newrange.Select(); // g_Newrange.SetNumberFormatLocal(COleVariant("@"));g_Newrange.SetItem(_variant_t((long)j),_variant_t((long)0),COleVariant(CTempSNnumber));if(j<3){g_Newrange.SetItem(_variant_t((long)j),_variant_t((long)1),_variant_t(CSLogistics+CSLogisticsNumber));}// g_Newrange.SetItem(_variant_t((long)j),_variant_t((long)2),_variant_t(CSLogisticsNumber));//CSLogisticsNumber// //水平對齊:默認=1,居中=-4108,左=-4131,右=-4152 //垂直對齊:默認=2,居中=-4108,左=-4160,右=-4107 //設(shè)置齊方式為水平垂直居中 // g_Newrange.SetHorizontalAlignment(_variant_t((long)-4131)); // g_Newrange.SetVerticalAlignment(_variant_t((long)-4160)); ////填入的sn自動加1UI64SNnumber++;}g_Newbook.SaveAs(COleVariant(SaveExcelPath), covOptional,covOptional, covOptional,covOptional, covOptional, (long)0, covOptional, covOptional, covOptional,covOptional, covOptional);// //釋放對象(相當重要!) // g_book.ReleaseDispatch(); // g_books.ReleaseDispatch(); // g_range.ReleaseDispatch(); // g_sheet.ReleaseDispatch(); // // // //退出程序 // g_app.Quit(); // //m_ExlApp一定要釋放,否則程序結(jié)束后還會有一個Excel進程駐留在內(nèi)存中,而且程序重復(fù)運行的時候會出錯 // g_app.ReleaseDispatch();g_Newbooks.Close();g_Newapp.Quit(); g_Newrange.ReleaseDispatch(); g_Newsheet.ReleaseDispatch(); g_Newsheets.ReleaseDispatch(); g_Newbook.ReleaseDispatch(); g_Newbooks.ReleaseDispatch(); g_Newapp.ReleaseDispatch(); return 0; }void CExcelmadetoolDlg::Onaddr() { COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR); CFileDialog dlg(true,"配置文件",NULL,0, "表格文件(.xls)|*.xls|表格文件(.xlsx)|*.xlsx");//打開文件if(IDOK==dlg.DoModal())strADDRPath =dlg.GetPathName();//獲取所有的工作簿if(!g_app.CreateDispatch("Excel.Application")){AfxMessageBox("無法啟動Excel服務(wù)器");return;}// g_books = g_app.GetWorkbooks(); //用來鎖定對應(yīng)的工作簿 g_books.AttachDispatch(g_app.GetWorkbooks(),true); g_book.AttachDispatch(g_books.Add(_variant_t(strADDRPath)),true);/*g_book = g_books.Open( strADDRPath,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional);*///得到Worksheets,工作表g_sheets.AttachDispatch(g_book.GetWorksheets(),true);g_sheet=g_sheets.GetItem(COleVariant((short)1));//獲得使用的區(qū)域g_range.AttachDispatch(g_sheet.GetUsedRange(),true);//獲取使用的行數(shù)int usedrowNum=0;g_range.AttachDispatch(g_range.GetRows(),true);usedrowNum=g_range.GetCount(); impliedSNAllLine=usedrowNum;//給控件設(shè)立建表默認行CString CTempSNLine;CTempSNLine.Format(_T("%d"),impliedSNAllLine);pBoxEnd-> SetWindowText(CTempSNLine);//獲取使用的列數(shù)int usedrowCol=0;g_range.AttachDispatch(g_range.GetColumns(),true);usedrowCol=g_range.GetCount();//獲取工作表的名字CString sheetName=g_sheet.GetName();//展現(xiàn)文檔//g_app.SetVisible(true);//釋放g_books.Close();g_app.Quit();g_range.ReleaseDispatch(); g_sheet.ReleaseDispatch(); g_sheets.ReleaseDispatch(); g_book.ReleaseDispatch(); g_books.ReleaseDispatch(); g_app.ReleaseDispatch(); }void CExcelmadetoolDlg::GetEditworth() {//取值CString strStart;CString strEnd;pBoxStart-> GetWindowText(strStart);pBoxEnd-> GetWindowText(strEnd);// int nGetInt = atoi( LPCTSTR(strEnd) );StrtoInt( &strStart, &startLine) ;StrtoInt( &strEnd, &EndLine) ;}void CExcelmadetoolDlg::StrtoInt(CString * const putStr, int * const putInt) {// const char * pchar=(LPSTR)(LPCSTR)(*putStr);*putInt = atoi(*putStr);}void CExcelmadetoolDlg::GetSNAllworth() {COleVariant vResult;COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); if( FAILED( CoInitialize(NULL) ) ){AfxMessageBox("初始化COM支持庫失敗!");}//沒有添加提示,工作簿創(chuàng)建// COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR); CFileDialog dlg(true,"配置文件",NULL,0, "表格文件(.xls)|*.xls|表格文件(.xlsx)|*.xlsx");//打開文件if(IDOK==dlg.DoModal())strADDRPath =dlg.GetPathName();//獲取所有的工作簿g_books = g_app.GetWorkbooks(); //用來鎖定對應(yīng)的工作簿 g_books.AttachDispatch(g_app.GetWorkbooks(),true); g_book = g_books.Open( strADDRPath,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional);//得到Worksheets,工作表g_sheets.AttachDispatch(g_book.GetWorksheets(),true);g_sheet=g_sheets.GetItem(COleVariant((short)1));//獲得使用的區(qū)域g_range.AttachDispatch(g_sheet.GetUsedRange(),true);//獲取使用的行數(shù)int usedrowNum=0;g_range.AttachDispatch(g_range.GetRows(),true);usedrowNum=g_range.GetCount(); //獲取使用的列數(shù)int usedrowCol=0;g_range.AttachDispatch(g_range.GetColumns(),true);usedrowCol=g_range.GetCount();//獲取第2行第一列的值g_range.AttachDispatch(g_sheet.GetCells());g_range.AttachDispatch(g_range.GetItem(COleVariant((long)2), COleVariant((long)1)).pdispVal);//行與列vResult = g_range.GetValue2();//獲取工作表的名字CString sheetName=g_sheet.GetName();//展現(xiàn)文檔//g_app.SetVisible(true);//釋放g_books.Close();g_app.Quit();g_range.ReleaseDispatch(); g_sheet.ReleaseDispatch(); g_sheets.ReleaseDispatch(); g_book.ReleaseDispatch(); g_books.ReleaseDispatch(); g_app.ReleaseDispatch(); }long CExcelmadetoolDlg::chToLong(const char *ch,int len) {long sum=0;unsigned __int64 aa=LONG_MAX;for(int i=len-1;i>=0;i--){long mm=long(ch[i]);long nn=mm - 48;sum+=(mm - 48) * pow(10,len-1-i);}return sum;}總結(jié)
以上是生活随笔為你收集整理的利用vc的mfc做的Excel表格处理工具的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GetDlgItem的用法
- 下一篇: 发送IP和MAC地址的方法