利用剪贴板实现PB与Excel的中文数据传输 |
PowerBuilder是面向对象的数据库开发工具之一,它可以操纵众多大型数据库和桌面数据库,支持多种硬件平台。但由于它提供的打印函数太少,使得制作打印报表很不方便,特别是对中国式报表,为此,我们在PB中常借助 Excel进行制表。但是在PB中用OLE与Excel进行中文数据传输时,数据传到Excel后会出现乱码,原来的中文变成了一堆不可辨认的字符。为解决此问题,我们可以借助Windows的剪贴板。 在PB中,先将数据放入剪贴板中,然后,运行一段事先在Excel中用VBA编写的宏代码,该宏的主要功能是从剪贴板中读取数据,再将数据填入Excel表格中。剪贴板在其中起到了“中介”的作用。具体实现方法如下: 首先,在PB下建立一窗口w—excel,然后在窗口中建立一个单行编辑框sle—text与一个按钮cb—trans,同时在按钮cb—trans的clicked事件中编写脚本,脚本为: //建立一个与Excel通讯的OLEObject OLEObject ExcelServer integer ExcelOK ExcelServer = CREATE OLEObject ConnectExcel: ExcelOK = ExcelServer.ConnectToNewObject( ″excel.application″ ) if ExcelOK<>0 then answer=MessageBox(″打印报表错误″,″连接不到 Excel″,Exclamation!,RetryCancel!) if answer=1 then goto ConnectExcel elseif answer=2 then return end if end if ExcelServer.Application.Visible = TRUE //显示Excel ExcelServer.WorkBooks.open(″FileName″) //连接到文件 //选择活动的Excel工作簿 ExcelServer.ActiveWorkBook.Sheets(″sheet1″).Select clipboard(sle—text) //将数据放入剪贴板中 //运行Excel文档中的VBA宏 //第一个参数为宏名,第二、三个参数为填入Excel表格的行列值 ExcelServer.application.run(″PutExcel″,1,1) 在Excel文档中编写的宏代码为: Const CF—TEXT = 1 Private Declare Function GetFocus Lib ″user32″ () As Long Private Declare Function OpenClipboard Lib ″user32″ (ByVal hWnd As Long) As Long Private Declare Function CloseClipboard Lib ″user32″ () As Long Private Declare Function GetClipboardData Lib ″user32″ (ByValwFormat As Long) As Long Private Declare Function IsClipboardFormatAvailable Lib ″user32″(ByVal wFormat As Long) As Long Private Declare Function GlobalLock Lib ″kernel32″ (ByVal hMen As Long) As Long Private Declare Function GlobalUnlock Lib ″kernel32″ (ByVal hMen As Long) As Long Private Declare Function GlobalSize Lib ″kernel32″ (ByVal hMen As Long) As Long Private Declare Function lstrcpy Lib ″kernel32″ Alias ″lstrcpyA″ (ByRef lpString1 As Any, ByRef lpString As Any) As Long Sub PutExcel(row As Integer, col As Integer) Dim ActivesheetName As String Dim ClipboardText As String ClipboardText = CLIP—TextGet() ′MsgBox ClipboardText ActivesheetName = ActiveSheet.Name Application.Worksheets(ActivesheetName).Cells(row,col).Value=ClipboardText End Sub Private Function CLIP—TextGet() As String Dim lpStr As Long Dim hGlobal As Long Dim tTempStr As String Dim bResult As Boolean Dim lResult As Long If OpenClipboard(GetFocus()) Then If IsClipboardFormatAvailable(CF—TEXT) Then hGlobal = GetClipboardData(CF—TEXT) If hGlobal <> 0 Then lpStr = GlobalLock(hGlobal) tTempStr = Space$(GlobalSize(lpStr)) lResult = lstrcpy(tTempStr, lpStr) bResult = GlobalUnlock(hGlobal) End If If Len(tTempStr) <> 0 Then CLIP—TextGet = Left$(tTempStr, InStr(tTempStr, vbNullChar)- 1) Else CLIP—TextGet = ″ ″ End If End If bResult = CloseClipboard() End If End Function |