c++ builder6 导出excel

wehuang2012 2015-06-25 12:21:47
之前一个 bcb5开发的程序 移植到 bcb6中 需添加 导出excel 功能。 现在的问题是 用ole 方法 程序报错
access violation at address 005AE277 .之前一个项目 用bcb6 开发的 同样代码 就没有报错。 刚开始学bcb 完善找不到方向 。求各位大神帮帮忙
...全文
2415 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
godanddog 2016-04-04
  • 打赏
  • 举报
回复
我去。。。挖坟贴
godanddog 2016-04-04
  • 打赏
  • 举报
回复
Sheet.h:

#ifndef SheetH
#define SheetH

class CWorkSheet
{
public:
    CWorkSheet();
    ~CWorkSheet();

    Variant *pSheet;

	Variant __fastcall GetCells(int i, int j);
    void __fastcall SetCells(int i, int j, int Value);
    void __fastcall SetCells(int i, int j, WideString Value);
	void __fastcall SetCells(int i, int j, WideString Value, int Width);

	int iRows;
	int iColumns;

	WideString __fastcall GetName();
	void __fastcall SetName(WideString Name);
	__property WideString Name = {read = GetName, write = SetName};
};
// ---------------------------------------------------------------------------
#endif
Sheet.cpp


#include <vcl.h>
#pragma hdrstop

#include <utilcls.h>
#include "Sheet.h"

// ---------------------------------------------------------------------------
#pragma package(smart_init)

CWorkSheet::CWorkSheet()
{
}

CWorkSheet::~CWorkSheet()
{
}

Variant __fastcall CWorkSheet::GetCells(int i, int j)
{
	return pSheet->OlePropertyGet("Cells", i, j).OlePropertyGet("value");
}

void __fastcall CWorkSheet::SetCells(int i, int j, int Value)
{
	pSheet->OlePropertyGet("Cells", i, j).OlePropertySet("value", Value);
}

void __fastcall CWorkSheet::SetCells(int i, int j, WideString Value)
{
	pSheet->OlePropertyGet("Cells", i, j).OlePropertySet("value", Value);
}

// ---------------------------------------------------------------------
void __fastcall CWorkSheet::SetCells(int i, int j, WideString Value, int Width)
{
	pSheet->OlePropertyGet("Cells", i, j).OlePropertySet("value", Value);
	pSheet->OlePropertyGet("Columns",j).OlePropertySet("ColumnWidth", Width);
}
// -----------------------------------------------------------------------

WideString __fastcall CWorkSheet::GetName()
{
	return VarToWideStr(pSheet->OlePropertyGet("name"));
}

void __fastcall CWorkSheet::SetName(WideString Name)
{
	pSheet->OlePropertySet("name", Name);
}
Excel.h

// ---------------------------------------------------------------------------

#ifndef ExcelH
#define ExcelH
// ---------------------------------------------------------------------------
#include "Sheet.h"

class CExcel
{
private:
	bool __fastcall OpenExcel();
	bool __fastcall NewExcel();

	int iCurrSheet;

	WideString _FileName;
	Variant vEx;
	Variant vWb;
	Variant vSh;

	CWorkSheet *pWorkSheet;

public:
	CExcel();
	CExcel(WideString FileName);
	~CExcel();

	bool __fastcall SaveExcel();
	bool __fastcall SaveAsExcel(WideString Name);
	void __fastcall CloseExcel();

	int iSheetCount;

	CWorkSheet* __fastcall GetSheet(int i);
};

#endif
excel.cpp

// ---------------------------------------------------------------------------
#include <vcl.h>

#pragma hdrstop

#include "Excel.h"
#include <utilcls.h>
#include <ComObj.hpp>
// ---------------------------------------------------------------------------
#pragma package(smart_init)

CExcel::CExcel()
{
	iCurrSheet = 0;
	pWorkSheet = new CWorkSheet();
	NewExcel();
}

CExcel::CExcel(WideString FileName)
{
	_FileName  = FileName;
	pWorkSheet = new CWorkSheet();
	OpenExcel();
}

CExcel::~CExcel()
{
	CloseExcel();
}

bool __fastcall CExcel::OpenExcel()
{
	try
	{
		CoInitialize(NULL);

		vEx = CreateOleObject("Excel.Application");
		vEx.OlePropertySet("Visible", false);
		vEx.OlePropertySet("DisplayAlerts", false);
		vEx.OlePropertyGet("WorkBooks").OleProcedure("Open",_FileName.c_bstr());

		vWb = vEx.OlePropertyGet("ActiveWorkBook");
		vSh = vWb.OlePropertyGet("ActiveSheet");
		pWorkSheet->pSheet = &vSh;
		iSheetCount = vWb.OlePropertyGet("sheets").OlePropertyGet("count");


		return true;
	}
	catch (...)
	{
		return false;
	}
}

bool __fastcall CExcel::NewExcel()
{
	try
	{
		CoInitialize(NULL);
		vEx = Variant::CreateObject("Excel.Application");
		vEx.OlePropertySet("Visible", false);
		vEx.OlePropertyGet("WorkBooks").OleFunction("Add");

		vWb = vEx.OlePropertyGet("ActiveWorkBook");
		vSh = vWb.OlePropertyGet("ActiveSheet");
		pWorkSheet->pSheet = &vSh;
		iSheetCount = vWb.OlePropertyGet("sheets").OlePropertyGet("count");

		return true;
	}catch (...)
	{
		return false;
	}
}

// ---------------------------------------------------------------------

bool __fastcall CExcel::SaveExcel()
{
	try
	{
		vWb.OleFunction("save");
		return true;
	}
	catch (...)
	{
		return false;
	}
}

bool __fastcall CExcel::SaveAsExcel(WideString Name)
{
AnsiString sFileName;

	sFileName = Name;
	if (FileExists(Name))
		DeleteFile(sFileName);

	try
	{
		vWb.OleFunction("SaveAs", Name.c_bstr());
		_FileName = Name;
		return true;
	}catch (...)
	{
		return false;
	}
}

void __fastcall CExcel::CloseExcel()
{
	if( NULL != pWorkSheet )
	{
		delete pWorkSheet;
		pWorkSheet = NULL ;
	}

	vWb.OleFunction("close");
	vEx.OleFunction("quit");
	vWb = Unassigned;
	vEx = Unassigned;

	CoUninitialize();
}

// ---------------------------------------------------------------------
CWorkSheet *__fastcall CExcel::GetSheet(int i)
{
	if (i == iCurrSheet)
	{
		return pWorkSheet;
	}
	else if (i < 1 || i > iSheetCount)
	{
		return NULL;
	}
	else
	{
		iCurrSheet = i;
	}

	vSh 			     = vWb.OlePropertyGet("Sheets", i);
	pWorkSheet->pSheet   = &vSh;
	pWorkSheet->iRows    = vSh.OlePropertyGet("UsedRange").OlePropertyGet("Rows").OlePropertyGet("count");
	pWorkSheet->iColumns = vSh.OlePropertyGet("UsedRange").OlePropertyGet("Columns").OlePropertyGet("count");

	return pWorkSheet;
}
没注释,请将就着看吧
cptang 2016-02-22
  • 打赏
  • 举报
回复
ehlib CGrid 都自带的导出功能
缘中人 2016-01-21
  • 打赏
  • 举报
回复
是的,grideh也带导出功能
麻酱面条 2016-01-21
  • 打赏
  • 举报
回复
用第三方插件 DevExpress ,里面的CGrid控件带导出成excel功能
Leighf 2016-01-14
  • 打赏
  • 举报
回复
//---------------------------------------------------------------------------
//功能: 导出EXCEL                                                        ,保存路径       ,是否预览
//---------------------------------------------------------------------------
void __fastcall TfrmMain::DBGToExcel(TADOQuery * ADOQuery, TDBGrid * DBGrid, String XlsFile, bool PreView)
{
    ADOQuery->First();
    if (ADOQuery->RecordCount == 0)
    {
        MessageBox(NULL, "无导出内容,操作取消!", "提示", MB_OK | MB_ICONINFORMATION);
        return;
    }

    TFileStream *fs=new TFileStream(XlsFile,fmCreate);
    String lf = "\r\n";      // 换行符
    String tab = char(9);    // 换列符
    String v;
    //导出字段名
    for (int i = 0; i < DBGrid->Columns->Count; i++)
    {
        if (DBGrid->Columns->Items[i]->Visible == true)
        {
            v = DBGrid->Columns->Items[i]->Title->Caption;//    FieldName;
            v = v + tab;    // 下一列
            fs->Write((void *)v.c_str(),v.Length());
        }
    }
    //导出字段内容
    fs->Write((void *)lf.c_str(),lf.Length());  //下一行

    for (int j = 0;j < ADOQuery->RecordCount; j++)
    {
        for (int i = 0;i < DBGrid->Columns->Count; i++)
        {
            if (DBGrid->Columns->Items[i]->Visible == true)
            {
                v = ADOQuery->Fields->Fields[i]->AsString.Trim();
                v = v + tab;    // 下一列
                fs->Write((void *)v.c_str(),v.Length());
            }
        }
        fs->Write((void *)lf.c_str(),lf.Length());  //下一行
        ADOQuery->Next();
    }
    delete fs;

    if (PreView)
    	ShellExecute(NULL,"open",XlsFile.c_str(),NULL,NULL,SW_SHOW);
    else
    	MessageBox(NULL, "导出完毕!", "提示", MB_OK | MB_ICONINFORMATION);
}
scsun 2015-07-22
  • 打赏
  • 举报
回复
客户端程序主机先要安装office。
jamesyue2008 2015-06-30
  • 打赏
  • 举报
回复
完整代码。 #define PG OlePropertyGet #define PS OlePropertySet #define OP OleProcedure #define OF OleFunction Variant Ex, Wb, Sheet; AnsiString FN = ""; AnsiString row = ""; try { FN = GetCurrentDir()+"\\Excel\\CuStyle.xls"; if(!FileExists(FN)) { Application->MessageBox(L"报表模板文件不存在,无法打开!",L"错误",MB_ICONSTOP|MB_OK); return; } try { Ex = Variant::CreateObject("Excel.Application"); } catch(...) { Application->MessageBox(L"无法启动Excel",L"错误",MB_ICONSTOP|MB_OK); return; } Ex.PS("Visible",false); Ex.PG("WorkBooks").OP("Open",FN.c_str()); Wb = Ex.PG("ActiveWorkBook"); AnsiString shname = "Style"; Sheet = Wb.PG("sheets", shname.c_str()); // Sheet.PG("Range","A2:I3000").OP("Clear"); int iRows, LI; LI = OrdHis->RecordCount; OrdHis->First(); for(iRows=2;iRows<LI+2;iRows++) { Sheet.PG("Cells",iRows,1).PS("Value",OrdHis->Fields->Fields[0]->AsAnsiString.c_str()); Sheet.PG("Cells",iRows,2).PS("Value",OrdHis->Fields->Fields[1]->AsAnsiString.c_str()); Sheet.PG("Cells",iRows,3).PS("Value",OrdHis->Fields->Fields[2]->AsFloat); Sheet.PG("Cells",iRows,4).PS("Value",OrdHis->Fields->Fields[3]->AsFloat); Sheet.PG("Cells",iRows,5).PS("Value",OrdHis->Fields->Fields[4]->AsFloat); Sheet.PG("Cells",iRows,6).PS("Value",OrdHis->Fields->Fields[5]->AsFloat); Sheet.PG("Cells",iRows,7).PS("Value",OrdHis->Fields->Fields[6]->AsAnsiString.c_str()); Sheet.PG("Cells",iRows,8).PS("Value",OrdHis->Fields->Fields[7]->AsAnsiString.c_str()); OrdHis->Next(); } row = AnsiString().sprintf("%d:5000", iRows); Sheet.PG("Rows", WideString(row)).OP("delete"); Wb.OP("Save"); Wb.OP("Close"); Ex.OF("Quit"); Ex = Unassigned; Wb = Unassigned; Sheet = Unassigned; } catch(...) { Application->MessageBox(L"操作Excel表格失败!",L"错误",MB_ICONSTOP|MB_OK); Wb.OP("Save"); Wb.OP("Close"); Ex.OF("Quit"); Ex = Unassigned; Wb = Unassigned; Sheet = Unassigned; } ShowMessage("数据成功导出...");
bigfog 2015-06-26
  • 打赏
  • 举报
回复
使用ole需要电脑中必须先安装了office,不然就出错 在妖哥网站有几篇相关文章,你可以参考一下 http://www.ccrun.com/page.asp?c=5&s=13
|????| 2015-06-25
  • 打赏
  • 举报
回复
求源码.(..........)

604

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder VCL组件使用和开发
社区管理员
  • VCL组件使用和开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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