如何在MS WORD中将文本插入表格? [英] How to insert text into tables in MS WORD ?

查看:104
本文介绍了如何在MS WORD中将文本插入表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!



我想首先感谢所有花时间查看此主题并尝试提供帮助的人。



我制作了一张带有桌子的MS Word文件。表有4列。



我想使用C ++和纯Win32 API将随机文本插入列中。



我相信这可以通过OLE和自动化完成,但我是新手,所以如果这是唯一的方法,请通过发布一些示例代码示例帮助我,如果这不是什么大不了的事,所以我可以看到使用OLE和自动化背后的逻辑,我将非常感激,因为我无法处理MSDN上的在线文档。



那将是所有,我只需要帮助,在我看来,简单的任务 - >使用一些随机文本填写MS Word文档中的表格。



编辑:

--------- ------------------------------------------------ <无线电通信/>


我已经决定使用OLE和C ++来完成这项任务,遵循本文的主题:

http://support.microsoft.com/kb/216686/en-us [ ^ ]



我设法打开了Word文件,让它看不见,但我需要帮助选择现有的表格。



现在已经足够了,因为它可以让我尝试插入文本我自己的桌子。



这是代码:



注意:

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



AutoWrap()中提供的句柄适用于如果发生错误必须关闭的对话框,其他一切都是相同的。



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



Hello everyone!

I would like to start by saying thanks to everyone who takes some time to view this thread and try to help.

I have made a MS Word document, with a table. Table has 4 columns.

I would like to insert random text into columns, using C++ and pure Win32 API.

I believe this can be done via OLE and automation, but I am new to that, so If that is the only way to do it, please help me by posting some sample code example, if that is not a big deal, so I can see the logic behind using OLE and automation, I would be very grateful, since I couldn't handle the online documentation on MSDN.

That would be all, I just need help for this, in my opinion, simple task-> to fill a table in document made in MS Word with some random text.


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

I have decided to use OLE and C++ for this task, following the exaple from this article:
http://support.microsoft.com/kb/216686/en-us[^]

I have managed to open the Word file, make it invisible, but I need help with selecting the existing table.

That would be enough for now, since it would enable me to try inserting text into table on my own.

Here is the code:

NOTE:
-----------------------

The handle provided in AutoWrap() is for a dialog that must be closed if error occurs, everything else is the same.

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

HRESULT AutoWrap(HWND hwnd,int autoType, VARIANT *pvResult, IDispatch *pDisp, 
				 LPOLESTR ptName, int cArgs...)	
{
	// Begin variable-argument list...

	va_list marker;
	va_start(marker, cArgs);
	
	if(!pDisp)
	{
		MessageBox( NULL, L"NULL IDispatch passed to AutoWrap()", L"Error", MB_ICONERROR );
	    
		EndDialog(hwnd, IDCANCEL);
	}
	
	// Variables used...

	DISPPARAMS dp = { NULL, NULL, 0, 0 };
	DISPID dispidNamed = DISPID_PROPERTYPUT;
	DISPID dispID;
	HRESULT hr;
	wchar_t buf[200];
	char szName[200];
	    
	// Convert down to ANSI

	WideCharToMultiByte( CP_ACP, 0, ptName, -1, szName, 256, NULL, NULL );
	    
	// Get DISPID for name passed...

	hr = pDisp->GetIDsOfNames( IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID );
	
	if(FAILED(hr)) 
	{
		swprintf_s( buf, L"IDispatch::GetIDsOfNames(\"%s\") failed with error 0x%08lx", 
			szName, hr );

		MessageBox( NULL, buf, L"AutoWrap()", MB_ICONERROR );

	    return hr;
	}
	    
	// Allocate memory for arguments...

	VARIANT *pArgs = new VARIANT[cArgs+1];

	// Extract arguments...

	for( int i=0; i<cArgs; i++ ) 
	{
		pArgs[i] = va_arg(marker, VARIANT);
	}
	    
	// Build DISPPARAMS

	dp.cArgs = cArgs;
	dp.rgvarg = pArgs;
	    
	// Handle special-case for property-puts!

	if(autoType & DISPATCH_PROPERTYPUT) 
	{
		dp.cNamedArgs = 1;
	    dp.rgdispidNamedArgs = &dispidNamed;
	}
	    
	// Make the call!

	hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, autoType, &dp, pvResult,
		NULL, NULL);

	if( FAILED(hr) ) 
	{
		swprintf_s(buf, L"IDispatch::Invoke(\"%s\"=%08lx) failed with error 0x%08lx", 
			szName, dispID, hr);

	    MessageBox( NULL, buf, L"AutoWrap()", MB_ICONERROR );

	    return hr;
	}

	// End variable-argument section...

	va_end(marker);
	    
	delete [] pArgs;
	    
	return hr;
}





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



当按下对话框按钮时,打开单词并用一些文字填充预制表:



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





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

When dialog button is pressed, open word and fill pre made table with some text:

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

case IDOK:
{
	// Initialize COM for this thread...

	CoInitialize(NULL);
	
	// Get CLSID for our server...

	CLSID clsid;
				
	HRESULT hr = CLSIDFromProgID(L"Word.Application", &clsid);
	
	if(FAILED(hr)) 
	{
		MessageBox( NULL, L"CLSIDFromProgID() failed", L"Error", 
						MB_ICONERROR );

		EndDialog(hwnd, IDCANCEL);
	}

	// Start server and get IDispatch...

	IDispatch *pWordApp;

	hr = CoCreateInstance( clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, 
					(void **)&pWordApp );
				
	if(FAILED(hr)) 
	{
		MessageBox( NULL, L"Word not registered properly", L"Error", 
						MB_ICONERROR );

		EndDialog(hwnd, IDCANCEL);
	}
	
	// Make it visible (i.e. app.visible = 1)

	{
		VARIANT x;
		x.vt = VT_I4;
		x.lVal = 1;	//	ako je 0 -> nevidljiva!!!
		AutoWrap( hwnd, DISPATCH_PROPERTYPUT, NULL, pWordApp, 
						L"Visible", 1, x);
	}
				
	// GetDocuments

	IDispatch *pDocuments;
	{
		VARIANT result;
		VariantInit(&result);
					
		hr = AutoWrap( hwnd, DISPATCH_PROPERTYGET, &result, pWordApp, 
						L"Documents", 0);

		pDocuments = result.pdispVal;
	}
	
	// OpenDocument

	IDispatch *pActiveDocument; 
	{
		/********* get current file path ****/

		wchar_t tmp[ _MAX_PATH ];

		memset( &tmp, '\0', sizeof(tmp) );

		if( DWORD nSize = GetModuleFileName( NULL, tmp, _MAX_PATH ) )
		{
			for (int i = nSize - 1; i >= 0; i--)
			{
				if ( tmp[i] == L'\\' || tmp[i] == L'/')
				{
					tmp[i + 1] = L'\0';
					nSize = i + 1;
					break;
				}
			}

			// concat printing folder and resource to manipulate with

			wcscat_s( tmp, _MAX_PATH, L"print\\Tabela.docx" );
		}
		else
		   {
			MessageBox( NULL, L"Грешка при учитавању ресурса за штампу!", 
								L"", MB_ICONERROR );
								
			EndDialog(hwnd, IDCANCEL);
		   }

		/************** open Word *****************/

		VARIANT result;
		VariantInit(&result);
		VARIANT x;
		x.vt = VT_BSTR;
		x.bstrVal = ::SysAllocString(tmp);

		AutoWrap( hwnd, DISPATCH_METHOD, &result, pDocuments, 
						L"Open", 1, x );

		pActiveDocument = result.pdispVal;

		SysFreeString(x.bstrVal);
	}


	MessageBox( hwnd, L"Added to give me time to see the effects", L"", MB_OK );

	// close Word

	{
		VARIANT x;
		x.vt = VT_BOOL;
		x.boolVal = false;

		AutoWrap( hwnd, DISPATCH_METHOD, NULL, pActiveDocument, L"Close", 
						1, x );

		AutoWrap( hwnd, DISPATCH_METHOD, NULL, pWordApp, L"Quit", 0);
	}	

	pActiveDocument->Release();
	pDocuments->Release();
	pWordApp->Release();

	// Uninitialize COM for this thread...

	CoUninitialize();
}

break;







谢谢。



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





我在MS Visual Studio Express 2008,Windows XP,C ++中使用纯WIN32 API。




Thank you.

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


I work in MS Visual Studio Express 2008, on Windows XP, in C++, using pure WIN32 API.

推荐答案

看看这里:

如何:以编程方式创建Word表格 [ ^ ]

如何to:以编程方式向Word表格中的单元格添加文本和格式 [ ^ ]

如何:以编程方式将行和列添加到Word表格 [ ^ ]

如何to:以编程方式使用文档属性填充Word表格 [ ^ ]

如何:插入表到文字处理文档(Open XML SDK) [ ^ ]



启动是否足够?
Have a look here:
How to: Programmatically Create Word Tables[^]
How to: Programmatically Add Text and Formatting to Cells in Word Tables[^]
How to: Programmatically Add Rows and Columns to Word Tables[^]
How to: Programmatically Populate Word Tables with Document Properties[^]
How to: Insert a table into a word processing document (Open XML SDK)[^]

Is it enough for start?


对于C ++,你可以从



使用Visual C ++的办公自动化

http://support.microsoft.com/kb/1 96776 / zh-CN



如何在不使用MFC或#import的情况下从C ++自动化Excel

http://support.microsoft.com/kb/216686/en-us



使用C ++的MS Office OLE自动化

http://www.codeproject.com/Articles/34998/MS-Office-OLE-Automation-Using-C



按照MS Office OLE自动化使用C ++手册进行操作





  • 选择键盘宏并指定宏的键
  • 启动宏录制后,执行自动化操作
  • 停止宏
  • 转到工具 - > Macro-> Visual Basic编辑器(F11)
  • 在NewMacros下,您可以在最后看到录制的宏
For C++ you could start with

Office Automation Using Visual C++
http://support.microsoft.com/kb/196776/en-us

How to automate Excel from C++ without using MFC or #import
http://support.microsoft.com/kb/216686/en-us

MS Office OLE Automation Using C++
http://www.codeproject.com/Articles/34998/MS-Office-OLE-Automation-Using-C

Followin the Manual for "MS Office OLE Automation Using C++"


  • Choose a keyboard macro and assign a key for the macro
  • After the macro recording has been started, do what you want get automated
  • Stop macro
  • Go to Tools->Macro->Visual Basic Editor (F11)
  • Under "NewMacros", you can see your recorded macro at the end
Selection.TypeText Text:="one"
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:="two"
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:="thre"
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:="four"





编辑:



在code.msdn.microsoft找到更多源代码

C ++ app自动化Word(CppAutomateWord)

http://code.msdn.microsoft.com/office/CppAutomateWord-28938be1 [ ^ ]


感谢会员 Maciej Los merano 提交的链接,我能够设计出一个解决方案。



它包含此链接 http:// msdn。 microsoft.com/en-us/library/Microsoft.Of fice.Interop.Word%28v = office.14%29.aspx [ ^ ],结合CodeProject上的文章:使用C ++的MS Office OLE自动化 [ ^ ]。



使用Macro的建议在Word中作为解决方案的帮助最终帮助了我。



谢谢大家,你们两个都有我的5,我将正式接受你的解决方案。



你已经赢了!
Thanks to the links submitted by members Maciej Los and merano, I was able to engineer a solution.

It included this link http://msdn.microsoft.com/en-us/library/Microsoft.Office.Interop.Word%28v=office.14%29.aspx[^] , combined with the article here on CodeProject : MS Office OLE Automation Using C++[^] .

The advice to use Macro in Word as assistance for a solution was what helped me in the end.

Thank you guys, both of you have my 5, and I will officially accept both your solutions.

You have earned it!


这篇关于如何在MS WORD中将文本插入表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆