求救:怎样在VC中写数据到EXCEL文件中

jtsy 2000-12-12 09:02:00
怎样在VC中写数据到EXCEL文件中
...全文
476 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tasehouny 2001-06-11
  • 打赏
  • 举报
回复
还有一个问题,用上述方法后,文件可以正常生成,但是,而且我在程序中也显示的调用
rgMyRge.ReleaseDispatch();
wsMysheet.ReleaseDispatch();
wssMysheets.ReleaseDispatch();
wbMyBook.ReleaseDispatch();
wbsMyBooks.ReleaseDispatch();
ExcelApp.ReleaseDispatch();
ExcelApp.Quit();
但是,内存中仍然有一个EXCEL进程在运行?即使在我的程序完全关闭以后?

为什么EXCEL不能完全退出?



joybug 2001-06-11
  • 打赏
  • 举报
回复
HOWTO: Use MFC to Automate Excel and Create/Format a New Workbook

--------------------------------------------------------------------------------
The information in this article applies to:

Microsoft Visual C++, 32-bit Editions, versions 5.0, 6.0
Microsoft Excel 2000
The Microsoft Foundation Classes (MFC)
Microsoft Office 2000 Developer
Microsoft Excel 97 for Windows

--------------------------------------------------------------------------------


SUMMARY
This article shows how to automate Microsoft Excel 97 or Excel 2000 using the Microsoft Foundation Class (MFC) library, version 4.2 (installed with Microsoft Visual C++ versions 5.0 and 6.0).

The article describes a technique for using OLE automation to create/format a Microsoft Excel workbook; it introduces several methods/properties (from the Microsoft Excel type library) for adding data to the worksheet and formatting the worksheet.



Notes for Automating Microsoft Excel 2000
Some methods and properties have changed for Microsoft Excel 2000. For additional information about using the sample code described in this article with the Microsoft Excel 2000 type library,, please click the article number below to view it in the Microsoft Knowledge Base:
Q224925 INFO: Type Libraries for Office 2000 Have Changed



MORE INFORMATION
You can copy the code in this article to the message handler function of an event defined in an MFC .cpp file. However, the purpose of the code is to illustrate the process of using the IDispatch interfaces and member functions defined in the Excel8.olb type library. The primary benefit of this article, however, comes from reading and understanding the code in the example so that you can modify the example or write your own code to automate Microsoft Excel 97 using MFC.

Steps to Create the Project
Follow steps 1 through 12 in the following Microsoft Knowledge Base article to create a sample project that uses the IDispatch interfaces and member functions defined in the Excel8.olb type library:


Q178749 HOWTO: Create an Automation Project Using MFC and a Type Library
At the top of the AutoProjectDlg.cpp file, add the following line:


#include "excel8.h"
Add the following code to CAutoProjectDlg::OnRun() in the AutoProjectDLG.cpp file:


Sample Code
// Commonly used OLE variants.
COleVariant
covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

_Application app;
Workbooks books;
_Workbook book;
Worksheets sheets;
_Worksheet sheet;
Range range;
Font font;
Range cols;

// Start Excel and get Application object.
if(!app.CreateDispatch("Excel.Application"))
{
AfxMessageBox("Couldn't start Excel and get Application object.");
return;
}

//Get a new workbook.
books = app.GetWorkbooks();
book = books.Add (covOptional);

//Get the first sheet.
sheets =book.GetSheets();
sheet = sheets.GetItem(COleVariant((short)1));

//Fill cells A1, B1, C1, and D1 one cell at a time with "headers".
range = sheet.GetRange(COleVariant("A1"),COleVariant("A1"));
range.SetValue(COleVariant("First Name"));
range = sheet.GetRange(COleVariant("B1"),COleVariant("B1"));
range.SetValue(COleVariant("Last Name"));
range = sheet.GetRange(COleVariant("C1"),COleVariant("C1"));
range.SetValue(COleVariant("Full Name"));
range = sheet.GetRange(COleVariant("D1"),COleVariant("D1"));
range.SetValue(COleVariant("Salary"));

//Format A1:D1 as bold, vertical alignment = center.
range = sheet.GetRange(COleVariant("A1"), COleVariant("D1"));
font = range.GetFont();
font.SetBold(covTrue);
range.SetVerticalAlignment(
COleVariant((short)-4108)); //xlVAlignCenter = -4108

//Fill A2:B6 with an array of values (First & Last Names).
{
COleSafeArray saRet;
DWORD numElements[]={5,2}; //5x2 element array
saRet.Create(VT_BSTR, 2, numElements);

//Fill the 5x2 SafeArray with the following data:
// John Smith
// Tom Brown
// Sue Thomas
// Jane Jones
// Adam Johnson

FillSafeArray(L"John", 0, 0, &saRet);
FillSafeArray(L"Smith", 0, 1, &saRet);
FillSafeArray(L"Tom", 1, 0, &saRet);
FillSafeArray(L"Brown", 1, 1, &saRet);
FillSafeArray(L"Sue", 2, 0, &saRet);
FillSafeArray(L"Thomas", 2, 1, &saRet);
FillSafeArray(L"Jane", 3, 0, &saRet);
FillSafeArray(L"Jones", 3, 1, &saRet);
FillSafeArray(L"Adam", 4, 0, &saRet);
FillSafeArray(L"Johnson", 4, 1, &saRet);

range = sheet.GetRange(COleVariant("A2"), COleVariant("B6"));
range.SetValue(COleVariant(saRet));

saRet.Detach();
}

//Fill C2:C6 with a relative formula (=A2 & " " & B2).
range = sheet.GetRange(COleVariant("C2"), COleVariant("C6"));
range.SetFormula(COleVariant("=A2 & \" \" & B2"));

//Fill D2:D6 with a formula(=RAND()*100000) and apply a number
//format.
range = sheet.GetRange(COleVariant("D2"), COleVariant("D6"));
range.SetFormula(COleVariant("=RAND()*100000"));
range.SetNumberFormat(COleVariant("$0.00"));

//AutoFit columns A:D.
range = sheet.GetRange(COleVariant("A1"), COleVariant("D1"));
cols = range.GetEntireColumn();
cols.AutoFit();

//Manipulate a variable number of columns for Quarterly Sales Data.
{
short NumQtrs;
CString msg;
Range resizedrange;
Interior interior;
Borders borders;

//Determine how many quarters to display data for.
for(NumQtrs=1;NumQtrs<=3;NumQtrs++)
{
msg.Format("Enter sales data for %d quarter(s)?", NumQtrs);
if(AfxMessageBox(msg,MB_YESNO)==IDYES)
{
break;
}
}
msg.Format("Displaying data for %d quarters.", NumQtrs);
AfxMessageBox(msg);

//Starting at E1, fill headers for the number of columns selected.
range = sheet.GetRange(COleVariant("E1"), COleVariant("E1"));
resizedrange = range.GetResize(covOptional, COleVariant(NumQtrs));
resizedrange.SetFormula(
COleVariant("=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\""));
//Change the Orientation and WrapText properties for the headers.
resizedrange.SetOrientation(COleVariant((short)38));
resizedrange.SetWrapText(covTrue);
//Fill the interior color of the headers.
interior = resizedrange.GetInterior();
interior.SetColorIndex(COleVariant((short)36));

//Fill the columns with a formula and apply a number format.
range = sheet.GetRange(COleVariant("E2"), COleVariant("E6"));
resizedrange = range.GetResize(covOptional, COleVariant(NumQtrs));
resizedrange.SetFormula(COleVariant("=RAND()*100"));
resizedrange.SetNumberFormat(COleVariant("$0.00"));

//Apply borders to the Sales data and headers.
range = sheet.GetRange(COleVariant("E1"), COleVariant("E6"));
resizedrange= range.GetResize(covOptional, COleVariant(NumQtrs));
borders = resizedrange.GetBorders();
borders.SetWeight(COleVariant((short)2)); //xlThin = 2

//Add a Totals formula for the Quarterly sales data and apply a
//border.
range = sheet.GetRange(COleVariant("E8"), COleVariant("E8"));
resizedrange = range.GetResize(covOptional, COleVariant(NumQtrs));
resizedrange.SetFormula(COleVariant("=SUM(E2:E6)"));
borders = resizedrange.GetBorders();
{
Border bottomborder;
bottomborder = borders.GetItem((long)9);
bottomborder.SetLineStyle(
COleVariant((short)-4119)); //xlDouble = -4119
bottomborder.SetWeight(
COleVariant((short)4)); //xlThick = 4
}
}

//Make the application visible and give the user control of
//Microsoft Excel.
app.SetVisible(TRUE);
app.SetUserControl(TRUE);
Add the following function to AutoProjectDLG.cpp, locating it somewhere before CAutoProjectDlg::OnRun():


Sample Code
void FillSafeArray(OLECHAR FAR* sz, int iRow, int iCol,
COleSafeArray* sa)
{
VARIANT v;
long index[2];

index[0] = iRow;
index[1] = iCol;

VariantInit(&v);
v.vt = VT_BSTR;
v.bstrVal = SysAllocString(sz);
sa->PutElement(index, v.bstrVal);
SysFreeString(v.bstrVal);
VariantClear(&v);
}
In Developer Studio, run the application. When the dialog box appears (the example creates a dialog-based application), click the Run button.



Additional query words: Excel 8 8.0 XL97 XL8

zb_china 2001-06-07
  • 打赏
  • 举报
回复
?
zb_china 2001-05-15
  • 打赏
  • 举报
回复
loutingyv():
我时过了你的代码,在解决了没有指明头文件和缺少一个续行符这两个小问题之后,代码运行得很好。很抱歉我对数据库一无所知,不知如何往一个拥有多个表的Excel文件中填写数据,这个文件是预先写好的,不能对格式有任何改动,每个数据都有指定的位置,而且有些数据原来不是空的需要修改。我现在很急,如果你能指点一下,我将非常感激。
zb_china zb_china@sina.com
loutingyv 2000-12-14
  • 打赏
  • 举报
回复
to JTSY
问题解决了没有?
vcmfc 2000-12-13
  • 打赏
  • 举报
回复
使用DAO可能是较方便的.
Sniper 2000-12-13
  • 打赏
  • 举报
回复
用ODBC。
Sniper 2000-12-13
  • 打赏
  • 举报
回复
用ODBC应该可以吧。
sxbyl 2000-12-13
  • 打赏
  • 举报
回复
使用COM,你可以在MSDN中搜一下Excel MFC ,会有四个标题,分别是:
1、HOWTO: Automate Excel 97 Using MFC and Worksheet Functions
2、HOWTO: Use MFC to Automate Excel & Create/Format a New Workbook
3、HOWTO: Use MFC to Automate Excel 97 and Navigate Worksheets
4、HOWTO: Use MFC to Create a Microsoft Excel 97 Chart
里面有源代码,你稍加修改,即可达到目的
还有,你需要用ClassWizard添加Excel类,用Add Class的From a type library,在你的Office目录下找到Excel9.OLB,然后选择你需要的类就可以了
loutingyv 2000-12-13
  • 打赏
  • 举报
回复
以下是你要的:
void MyDemo::Put2Excel()
{
CDatabase database;
CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)";
CString sExcelFile = "c:\\demo.xls";
CString sSql;

TRY
{
sSql.Format("DRIVER={%s};DSN='';
FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",
sDriver, sExcelFile, sExcelFile);

if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
{
sSql = "CREATE TABLE demo (Name TEXT,Age NUMBER)";
database.ExecuteSQL(sSql);

sSql = "INSERT INTO demo (Name,Age) VALUES ('A',45)";
database.ExecuteSQL(sSql);

sSql = "INSERT INTO demo (Name,Age) VALUES ('B',30)";
database.ExecuteSQL(sSql);

sSql = "INSERT INTO demo (Name,Age) VALUES ('C',28)";
database.ExecuteSQL(sSql);
}
database.Close();
}
CATCH_ALL(e)
{
TRACE1("Driver not installed: %s",sDriver);
}
END_CATCH_ALL;
}

16,550

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Creator Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧