把MSHFlexGrid里数据导出至Excel
将DataGridView中的数据导出至Excel中(亲测成功)
将DataGridView中的数据导出至Excel(亲测成功)一、建立一个静态方法public static void ExportAsExcel(DataGridView dgv){OutputAsExcelFile(DGVHelper.DataGridViewToTable(dgv));}二、把DataGridView中的数据转换到DataTable中///<summary>///将DataGridView中的数据转换为DataTable包含隐藏列///</summary>///<param name="dgv"></param>///<returns></returns>public static DataTable DataGridViewToTable(DataGridView dgv){DataTable dt=new DataTable();//循环列标题名称,处理了隐藏的行不显示for(int count=0;count<dgv.Columns.Count;count++){if(dgv.Columns[count].Visible==true){dt.Columns.Add(dgv.Columns[count].HeaderText.ToString());}}//循环行,处理了隐藏的行不显示for(int count=0;count<dgv.Rows.Count;count++){DataRow dr=dt.NewRow();int curr=0;for(int countsub=0;countsub<dgv.Columns.Count;countsub++){if(dgv.Columns[countsub].Visible==true){if(dgv.Rows[count].Cells[countsub].Value!=null){dr[curr]=dgv.Rows[count].Cells[countsub].Value.ToString();}else{dr[curr]="";}curr++;}}dt.Rows.Add(dr);}return dt;}三、把DataTable中的数据导出到Excel中public static void OutputAsExcelFile(DataTable dt){if(dt.Rows.Count<=0){MessM.PromptInfo("提示","无数据!");return;}SaveFileDialog s=new SaveFileDialog{Title="保存Excel文件",Filter="Excel文件(*.xls)|*.xls",FilterIndex=1};if(s.ShowDialog()==DialogResult.OK)filePath=s.FileName;elsereturn;DTExportToExcel(dt);}///<summary>///第二步:导出dataTable到Excel///</summary>///<param name="dt"></param>private static void DTExportToExcel(DataTable dt){//第二步:导出dataTable到Excellong rowNum=dt.Rows.Count;//行数int columnNum=dt.Columns.Count;//列数Excel.Application m_xlApp=new Excel.Application{DisplayAlerts=false,//不显示更改提示Visible=false};Excel.Workbooks workbooks=m_xlApp.Workbooks;Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1try{string[,]datas=new string[rowNum+1,columnNum];for(int i=0;i<columnNum;i++)//写入字段datas[0,i]=dt.Columns[i].Caption;//Excel.Range range=worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[1, columnNum]);Excel.Range range=m_xlApp.Range[worksheet.Cells[1,1],worksheet.Cells[1, columnNum]];range.Interior.ColorIndex=15;//15代表灰色range.Font.Bold=true;range.Font.Size=10;int r=0;for(r=0;r<rowNum;r++){for(int i=0;i<columnNum;i++){object obj=dt.Rows[r][dt.Columns[i].ToString()];datas[r+1,i]=obj==null?"":"'"+obj.ToString().Trim();//在obj.ToString()前加单引號是为了防止自己主动转化格式}Application.DoEvents();//加入进度条}//Excel.Range fchR=worksheet.get_Range(worksheet.Cells[1,1], worksheet.Cells[rowNum+1,columnNum]);Excel.Range fchR=m_xlApp.Range[worksheet.Cells[1,1],worksheet.Cells[rowNum+1, columnNum]];fchR.Value2=datas;worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
如何把MSHFlexGrid里的数据导出至Excel
如何把MSHFlexGrid里的数据导出至Excel?用Adodc1做了查询语句,结果显示在一个MSHFlexGrid里面。
现在要求做一个按钮(Command1),点击它就把MSHFlexGrid里显示的数据导出至Excel表中。
就是一点这个按钮,就会自动打开Excel,然后数据就已经进去了,方便编辑和打印。
要求:代码详细,直接复制到Command1下就能用。
这块我不懂,所以不要搞什么子程序调用之类的,要有子程序也给直接调用好。
直接复制代码成功后,再追加100分。
把这个弄完工程就结了,再不用受罪了,哈哈!以下是精简后的代码,不清楚你工作中的一些细节,所以如有问题与我讨论Private Sub Command1_Click()MSFlexGrid1.Redraw = False '关闭表格重画,加快运行速度Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象Set xlBook = xlApp.Workbooks.Open(App.Path & "\对账模板.xls") '打开已经存在的EXCEL 工件簿文件xlApp.Visible = True '设置EXCEL对象可见(或不可见)Set xlsheet = xlBook.Worksheets("Sheet1") '设置活动工作表For R = 0 To MSFlexGrid1.Rows - 1 '行循环For C = 0 To MSFlexGrid1.Cols - 1 '列循环MSFlexGrid1.Row = RMSFlexGrid1.Col = CxlBook.Worksheets("Sheet1").Cells(R + 1, C + 1) = MSFlexGrid1.Text '保存到EXCEL Next CNext RMSFlexGrid1.Redraw = True'xlsheet.PrintOut '打印工作表xlApp.DisplayAlerts = False '不进行安全提示'xlBook.Close (False) '关闭工作簿Set xlsheet = NothingSet xlBook = NothingxlApp.QuitSet xlApp = NothingEnd Sub下面的代码就也能导出到EXCELDim xlApp As Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim i As Long, J As LongOn Error GoTo ErrorHandleSet xlApp = CreateObject( "Excel.Application ")Set xlBook = xlApp.Workbooks.AddSet xlSheet = xlBook.Worksheets(1)For i = 0 To MHFGrid.Rows - 1For J = 0 To MHFGrid.Cols - 1xlSheet.Cells(i + 1, J + 1).Value = MHFGrid.TextMatrix(i, J)Next JNext ixlSheet.Application.Visible = TrueSet xlSheet = NothingSet xlBook = NothingSet xlApp = NothingExit SubErrorHandle:MsgBox "错误:" & Err.Number & vbCrLf & Err.Description, vbOKOnly, "运行错误"如何将表中的数据导出到电子表格中作者:施进兵有很多方法都可将数据库中某个表的数据导出到电子表格中,例如通过创建Access.Application,可以利用Access本身的导出功能实现将表中的数据导出到电子表格中。
C#DataGridView导出excel的几种方法
C#DataGridView导出excel的⼏种⽅法第⼀种、⾸先本form上游datagridview的控件及数据,再建⼀个button控件作为导出按钮,在按钮click事件中写⼊以下代码此乃数据集的⽅式,即先将数据放⼊数据集表⾥作为对象与excel⼀⼀对应//保存⽂件对话框SaveFileDialog sfd = new SaveFileDialog();sfd.Filter = "Excel⽂件|*.xlsx|Word⽂件|*.docx";sfd.FilterIndex = 0;if (sfd.ShowDialog() == DialogResult.OK){string search = "select * from 旧备件表 where(0=0)";if (this.textBox1.Text.Length > 0){search = search + " and 物料编码=" + "'" + textBox1.Text + "'";}if (this.textBox2.Text.Length > 0){search = search + " and 设备号=" + "'" + textBox2.Text + "'";}if (this.textBox3.Text.Length > 0){search = search + " and 物料描述 like" + "'%" + textBox3.Text + "%'";//实现物料描述的模糊查询}if (this.textBox4.Text.Length > 0){search = search + " and 备件序列号 like" + "'%" + textBox4.Text + "%'";//实现备件序列号的模糊查询}//调⽤导出Excel的⽅法,传⼊DataTable数据表和路径SqlDataAdapter sda = new SqlDataAdapter(search, DataBase.GetSqlConnection());System.Data.DataTable dt = new System.Data.DataTable();//将数据库中查到的数据填充到DataTable数据表sda.Fill(dt);ExportExcel(dt, sfd.FileName);}}void ExportExcel(System.Data.DataTable dt, string filepath){//创建Excel应⽤程序类的⼀个实例,相当于从电脑开始菜单打开ExcelApplicationClass xlsxapp = new ApplicationClass();//新建⼀张Excel⼯作簿Workbook wbook = xlsxapp.Workbooks.Add(true);//第⼀个sheet页Worksheet wsheet = (Worksheet)wbook.Worksheets.get_Item(1);//将DataTable的列名显⽰在Excel表第⼀⾏for (int i = 0; i < dt.Columns.Count; i++){//注意Excel表的⾏和列的索引都是从1开始的wsheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;}//遍历DataTable,给Excel赋值for (int i = 0; i < dt.Rows.Count; i++){for (int j = 0; j < dt.Columns.Count; j++){//从第⼆⾏第⼀列开始写⼊数据wsheet.Cells[i + 2, j + 1] = dt.Rows[i][j];}}//保存⽂件wbook.SaveAs(filepath);//释放资源xlsxapp.Quit();}第⼆种、此乃直接将datagridview⾥的数据⼀⼀导出放⼊excel指定的单元格⾥。
vb用数组方式快速导出MSFlexGrid表格数据到Excel表格中
本来从MSFlexGrid或MSHFlexGrid导出数据到Excel中,是一个非常简单的问题,但论坛里还是经常有人问如何导出,有的虽然知道用单元格赋值方式循环导出,但速度太慢,因此写了一个通用的数据导出函数,由于以数组方式一次性赋值,运度速度得到了极大提升,需要的朋友可以参照以下代码,稍作修改,就可以写出用于其它表格控件向Excel导出数据的功能了。
Next
Next
'导出到Excel中
If StartRow < 1 Then StartRow = 1
If StartColumn < 1 Then StartColumn = 1
Set objApp = CreateObject("Excel.Application")
objApp.ScreenUpdating = False '禁止屏幕刷新
End Sub
Dim objApp As Object
Dim objWorkbook As Object
Dim objWorksheet As Object
Dim objRange As Object
Dim CellsData() As String
Dim i As Long, j As Long
Dim nRows As Long, nColumns As Long
代码如下:
Public Sub ExportToExcel(ByRef objGrid As MSHFlexGrid, ByVal strFileName As String, Optional StartRow As Long = 1, Optional StartColumn As Long = 1)
MShFlexGrid1如何导出Excel表格
'MSHFlexGrid控件的导出Public Function FlexExportE(ByV al Flex1 As MSHFlexGrid, ByV al CommonDialog1 As CommonDialog) mvarV ersion = vbLBV5Dim SaveFilePath As StringDim EXEString As StringDim i As Integer, j As IntegerDim InsertAmount As IntegerDim WS As DAO.WorkspaceDim DB As DAO.DatabaseDim TABL As DAO.TableDefDim RS As DAO.Recordset'On Error GoTo err_handle' On Error Resume NextWith CommonDialog1.CancelError = False.Filter = "Excel文件(*.xls)|*.xls".DialogTitle = "将数据导出到Excel表(5.0)".ShowOpenIf Trim(.FileName) = "" ThenExit FunctionEnd IfSaveFilePath = .FileNameEnd With'If flex1.ColumnHeaders.Count <= 0 Then' Exit Sub'End IfDim MyFileMyFile = Dir(SaveFilePath)Dim Msg As IntegerIf MyFile <> "" ThenMsg = MsgBox("是否要覆盖原文件!", vbInformation + vbY esNo, "提示")If Msg = 7 ThenExit FunctionElseKill (MyFile)End IfEnd IfSet WS = DBEngine.CreateWorkspace("WS", "Admin", "", dbUseJet)Dim mdbFilemdbFile = Dir(App.Path & "\report\FlexToExcel.mdb")If mdbFile <> "" ThenKill App.Path & "\report\FlexToExcel.mdb"End If' Set DB = WS.CreateDatabase(App.Path & "\report\FlexToExcel.mdb", dbLangGeneral, dbEncrypt) Set DB = WS.CreateDatabase(App.Path & "\report\FlexToExcel.mdb", dbLangGeneral, dbEncrypt)Set TABL = DB.CreateTableDef("Excel")' For i = 1 To Flex1.Cols - 1' TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, i), dbText, 250)' 'TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, i), dbSingle, 250)' Next iTABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0,0), dbText, 250)TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 1), dbText, 250) 'emp_id1 TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 2), dbText, 250) '部门TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 3), dbText, 250) '工号TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 4), dbText, 250) '姓名TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 5), dbText, 250) '月份TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 6), dbDouble, 250) 'baseTABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 7), dbDouble, 250) '岗位TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 8), dbDouble, 250) '津贴TABL.Fields.Append TABL.CreateField(Flex1.TextMatrix(0, 9), dbDouble, 250) '技能DB.TableDefs.Append TABLSet RS = DB.OpenRecordset("Excel")If Flex1.Rows > 1 ThenInsertAmount = Flex1.Cols - 1For i = 1 To Flex1.Rows - 1RS.AddNew'RS.Fields(0) = Flex1.ListItems.Item(i).Text'RS.Fields(0) = Flex1.TextMatrix(i, 1)For j = 0 To InsertAmountIf Flex1.TextMatrix(i, j) <> "" ThenRS.Fields(j) = Flex1.TextMatrix(i, j)ElseIf Flex1.TextMatrix(i, j) = "" ThenRS.Fields(j) = "//"End IfNext jRS.UpdateNext iEnd IfEXEString = "select * into [Excel " & Format(CStr(mvarVersion), "0.0") & ";database=" & SaveFilePat h & "].LBExcel from Excel" DB.Execute EXEStringRS.CloseDB.CloseWS.CloseKill App.Path & "\report\FlexToExcel.mdb"MsgBox "导出数据到Excel表成功!", vbInformation, "提示"Exit Functionerr_handle:Select Case ErrCase 53:Resume NextEnd SelectEnd Function。
将DELPHI中把数据库中数据导出到EXCEL中
将DELPHI中把数据库中数据导出到EXCEL中使用Delphi 控件方法在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。
1)打开ExcelExcelApplication1.Connect;2) 显示当前窗口:ExcelApplication1.Visible[0]:=True;3) 更改Excel 标题栏:ExcelApplication1.Caption := '应用程序调用Microsoft Excel';4) 添加新工作簿:ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0));5) 添加新工作表:var Temp_Worksheet: _WorkSheet;beginTemp_Worksheet:=ExcelWorkbook1.WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet;ExcelWorkSheet1.ConnectTo(Temp_WorkSheet);End;6) 打开已存在的工作簿:ExcelApplication1.Workbooks.Open (c:\a.xlsEmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,0)7) 设置第2个工作表为活动工作表:ExcelApplication1.WorkSheets[2].Activate; 或ExcelApplication1.WorksSheets[ 'Sheet2' ].Activate;8) 给单元格赋值:ExcelApplication1.Cells[1,4].V alue := '第一行第四列';9) 设置指定列的宽度(单位:字符个数),以第一列为例:ExcelApplication1.ActiveSheet.Columns[1].ColumnsWidth := 5;10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:ExcelApplication1.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米11) 在第8行之前插入分页符:ExcelApplication1.WorkSheets[1].Rows[8].PageBreak := 1;12) 在第8列之前删除分页符:ExcelApplication1.ActiveSheet.Columns[4].PageBreak := 0;13) 指定边框线宽度:ExcelApplication1.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;1-左2-右3-顶4-底5-斜( \ ) 6-斜( / )14) 清除第一行第四列单元格公式:ExcelApplication1.ActiveSheet.Cells[1,4].ClearContents;15) 设置第一行字体属性:ExcelApplication1.ActiveSheet.Rows[1] := '隶书';ExcelApplication1.ActiveSheet.Rows[1].Font.Color := clBlue;ExcelApplication1.ActiveSheet.Rows[1].Font.Bold := True;ExcelApplication1.ActiveSheet.Rows[1].Font.UnderLine := True;16) 进行页面设置:a.页眉:ExcelApplication1.ActiveSheet.PageSetup.CenterHeader := '报表演示';b.页脚:ExcelApplication1.ActiveSheet.PageSetup.CenterFooter := '第&P页';c.页眉到顶端边距2cm:ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;d.页脚到底端边距3cm:ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;e.顶边距2cm:ExcelApplication1.ActiveSheet.PageSetup.TopMargin := 2/0.035;f.底边距2cm:ExcelApplication1.ActiveSheet.PageSetup.BottomMargin := 2/0.035;g.左边距2cm:ExcelApplication1.ActiveSheet.PageSetup.LeftMargin := 2/0.035;h.右边距2cm:ExcelApplication1.ActiveSheet.PageSetup.RightMargin := 2/0.035;i.页面水平居中:ExcelApplication1.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;j.页面垂直居中:ExcelApplication1.ActiveSheet.PageSetup.CenterV ertically := 2/0.035;k.打印单元格网线:ExcelApplication1.ActiveSheet.PageSetup.PrintGridLines := True;17) 拷贝操作:a.拷贝整个工作表:ed.Range.Copy;b.拷贝指定区域:ExcelApplication1.ActiveSheet.Range[ 'A1:E2' ].Copy;c.从A1位置开始粘贴:ExcelApplication1.ActiveSheet.Range.[ 'A1' ].PasteSpecial;d.从文件尾部开始粘贴:ExcelApplication1.ActiveSheet.Range.PasteSpecial;18) 插入一行或一列:a. ExcelApplication1.ActiveSheet.Rows[2].Insert;b. ExcelApplication1.ActiveSheet.Columns[1].Insert;19) 删除一行或一列:a. ExcelApplication1.ActiveSheet.Rows[2].Delete;b. ExcelApplication1.ActiveSheet.Columns[1].Delete;20) 打印预览工作表:ExcelApplication1.ActiveSheet.PrintPreview;21) 打印输出工作表:ExcelApplication1.ActiveSheet.PrintOut;22) 工作表保存:if not ExcelApplication1.ActiveWorkBook.Saved thenExcelApplication1.ActiveSheet.PrintPreview;23) 工作表另存为:ExcelApplication1.SaveAs( 'C:\Excel\Demo1.xls' );24) 放弃存盘:ExcelApplication1.ActiveWorkBook.Saved := True;25) 关闭工作簿:ExcelApplication1.WorkBooks.Close;26) 退出Excel:ExcelApplication1.Quit;ExcelApplication1.Disconnect;Top2 楼songlian(雨)回复于2005-04-29 16:37:15 得分0把数据集导如导excel,adsdata可以换成任意你用导的数据集WriteExcel(AdsData:Tclientdataset; sName, Title: string);varExcelApplication1: TExcelApplication;ExcelWorksheet1: TExcelWorksheet;ExcelWorkbook1: TExcelWorkbook;i, j: integer;filename: string;beginfilename := concat(sName, '.xls');tryExcelApplication1 := TExcelApplication.Create(Application);ExcelWorksheet1 := TExcelWorksheet.Create(Application);ExcelWorkbook1 := TExcelWorkbook.Create(Application);ExcelApplication1.Connect;exceptApplication.Messagebox('Excel没有安装!','Hello',MB_ICONERROR + mb_Ok);Abort;end;tryExcelApplication1.Workbooks.Add(EmptyParam, 0);ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Worksheets[1] as _worksheet);AdsData.First;for j := 0 to AdsData.Fields.Count - 1 dobeginExcelWorksheet1.Cells.item[3, j + 1] := AdsData.Fields[j].DisplayLabel;ExcelWorksheet1.Cells.item[3, j + 1].font.size :='10';end;for i := 4 to AdsData.RecordCount + 3 dobeginfor j := 0 to AdsData.Fields.Count - 1 dobeginExcelWorksheet1.Cells.item[i, j + 1] :=AdsData.Fields[j].Asstring;ExcelWorksheet1.Cells.item[i, j + 1].font.size := '10';end;AdsData.Next;end;ExcelWorksheet1.Columns.AutoFit;ExcelWorksheet1.Cells.item[1, 2] := Title;ExcelWorksheet1.Cells.Item[1, 2].font.size :='14';ExcelWorksheet1.SaveAs(filename);Application.Messagebox(pchar('数据成功导出'+ filename),'信息化建设部',mb_Ok);finallyExcelApplication1.Disconnect;ExcelApplication1.Quit;ExcelApplication1.Free;ExcelWorksheet1.Free;ExcelWorkbook1.Free;end;end;。
关于vb如何从MSFlexGrid空间中把内容导入excel的方法
以下代码写在模块中:'MSHFlexGrid控件导出到ExcelPublic Function ExportFlexDataToExcel(flex As MSFlexGrid, g_CommonDialog As CommonDia log)On Error GoTo ErrHandlerDim xlApp As ObjectDim xlBook As ObjectDim Rows As Integer, Cols As IntegerDim iRow As Integer, hCol As Integer, iCol As IntegerDim New_Col As BooleanDim New_Column As Booleang_CommonDialog.CancelError = TrueOn Error GoTo ErrHandler' 设置标志g_CommonDialog.Flags = cdlOFNHideReadOnly' 设置过滤器g_CommonDialog.Filter = "All Files (*.*)|*.*|Excel Files" & _"(*.xls)|*.xls|Batch Files (*.bat)|*.bat"' 指定缺省的过滤器g_CommonDialog.FilterIndex = 2' 显示“打开”对话框g_CommonDialog.ShowSaveIf flex.Rows <= 1 ThenMsgBox "没有数据!", vbInformation, g_MsgtitleExit FunctionEnd IfSet xlApp = CreateObject("Excel.Application")Set xlBook = xlApp.Workbooks.AddxlApp.Visible = FalseWith flexRows = .RowsCols = .ColsiRow = 0iCol = 1For hCol = 0 To Cols - 1For iRow = 1 To RowsxlApp.Cells(iRow, iCol).Value = .TextMatrix(iRow - 1, hCol)Next iRowiCol = iCol + 1Next hColEnd WithWith xlApp.Rows(1).Font.Bold = True.Cells.Select.Columns.AutoFit.Cells(1, 1).Select' .Application.Visible = TrueEnd WithxlBook.SaveAs (g_CommonDialog.FileName)xlApp.Application.Visible = FalsexlApp.DisplayAlerts = FalsexlApp.QuitSet xlApp = Nothing '"交还控制给ExcelSet xlBook = Nothingflex.SetFocusMsgBox "数据已经导出到Excel中。
DELPHI如何将数据导出到指定格式的EXCEL模版
DELPHI如何将数据导出到指定格式的EXCEL模版DELPHI如何将数据导出到指定格式的EXCEL模版2011-10-31 14:27445人阅读评论(0)收藏举报参考代码1Delphi(Pascal) codepath:=ExtractFilePath(Application.ExeName);if self.OpenDialog1.Execute thenfilename:=self.OpenDialog1.FileName;trySelf.ExcelApplication1:=TExcelApplication.Create(self);Self.ExcelApplication1.Connect;exceptmessagebox(application.Handle,'无法生成Excel报表,请确定安装了Excel后重试','信息',mb_ok or mb_iconinformation);exit;end;Self.ExcelApplication1.Visible[0]:=true;self.ExcelApplication1.DisplayAlerts[0]:=False;self.ExcelApplication1.Workbooks.Open(filename,EmptyPara m,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,0);self.ExcelWorkbook1.ConnectT o(Self.ExcelApplication1.Work books[1]);self.ExcelWorksheet1:=TExcelWorkSheet.Create(self);self.ExcelWorksheet1.ConnectT o(Self.ExcelWorkbook1.Works heets[1] as _worksheet);i:=self.StringGrid2.RowCount;for j:=1to i-1dobeginxh:=Self.StringGrid2.Cells[0,j];pscj:=self.StringGrid2.Cells[2,j];kscj:=Self.StringGrid2.Cells[4,j];zpcj:=Self.StringGrid2.Cells[5,j];self.ExcelWorksheet1.cells.Item[l+j,m]:=pscj;self.ExcelWorksheet1.cells.Item[l+j,n]:=kscj;self.ExcelWorksheet1.cells.Item[l+j,k]:=zpcj;end;Self.ExcelWorksheet1.SaveAs(filename);Self.ExcelApplication1.Disconnect;Self.ExcelWorkbook1.Disconnect;Self.ExcelWorksheet1.Disconnect;Delphi(Pascal) codepath:=ExtractFilePath(Application.ExeName);if self.OpenDialog1.Execute thenfilename:=self.OpenDialog1.FileName;trySelf.ExcelApplication1:=TExcelApplication.Create(self);Self.ExcelApplication1.Connect;exceptmessagebox(application.Handle,'无法生成Excel报表,请确定安装了Excel后重试','信息',mb_ok or mb_iconinformation);e…tryexcel := CreateOleObject('Excel.Application'); WorkBook := excel.Workbooks.Add('模板的路径.xls'); Sheet := WorkBook.Worksheets[1];exceptexcel := NULL;DJShow('请先安装Excel97/2000。
FineReport报表打印导出EXCEL的四种方式
FineReport报表打印导出EXCEL的四种方式在实际的应用中会经常需要将数据导出成excel,导出的方式除原样导出还有分页导出、分页分sheet导出和大数据量导出。
对于excel 2003版,由于限制了每个sheet的最大行数和列数,大数据量导出时会默认时分多个sheet,而excel2007不会出现这样的问题。
这些导出方式在JAVA程序中分别有不同的接口来实现:1、原样导出原样导出就是不预览直接导出excel其程序接口代码如下:outputStream = new FileOutputStream(new File("E:\\ExcelExport.xls"));ExcelExporter excel = new ExcelExporter();//导出2007版outputStream = new FileOutputStream(new File("E:\\ExcelExport.xlsx")); excel Excel2007Exporter excel = new Excel2007Exporter();excel.export(outputStream, rworkbook);效果图:2、分页导出分页导出,如果报表模版是分页的,会按照分页的结果形式导出,重复的标题等也会重复。
其程序接口代码如下:outputStream = new FileOutputStream(new File("E:\\PageExcelExport.xls")); PageExcelExporter page = new PageExcelExporter(ReportUtils.getPaperSettingListFromWorkBook(rworkbook));//导出2007版outputStream = new FileOutputStream(new File("E:\\PageExcelExport.xlsx")); excel PageExcel2007Exporter page = new PageExcel2007Exporter(ReportUtils.getPaperSettingListFromWorkBook(rworkbook));page.export(outputStream, rworkbook);效果图:3、分页分sheet导出分页分Sheet导出时报表结果的每一页为一个Sheet保存在Excel文件中其代码如下:outputStream = new FileOutputStream(new File("E:\\PageSheetExcelExport.xls")); PageToSheetExcelExporter sheet = newPageToSheetExcelExporter(ReportUtils.getPaperSettingListFromWorkBook(rworkbook));//导出2007版outputStream = new FileOutputStream(new File("E:\\PageSheetExcelExport.xlsx")); excel PageToSheetExcel2007Exporter sheet = new PageToSheetExcel2007Exporter(ReportUtils.getPaperSettingListFromWorkBook(rworkbook)); sheet.export(outputStream, rworkbook);效果图:4、大数据量导出这是比较常见的,例如以50000行为一个excel文件其代码如下:outputStream = new FileOutputStream(new File("E:\\LargeExcelExport.zip")); LargeDataPageExcelExporter large = new LargeDataPageExcelExporter(ReportUtils.getPaperSettingListFromWorkBook(rworkbook), true); //导出2007版outputStream = new FileOutputStream(new File("E:\\LargeExcelExport.xlsx")); excel LargeDataPageExcel2007Exporter large = new LargeDataPageExcel2007Exporter(ReportUtils.getPaperSettingListFromWorkBook(rworkbook), true);large.export(outputStream, rworkbook);对于大数据量导出报表时,可能会出现如下两种情况:一,导出成功,数据会显示在多个Sheet中;二,二,导出失败,导出的Excel内容无效。
VB编程:使用MSHFlexGrid控件与Excel互传数据
VB编程:使用MSHFlexGrid控件与Excel互传数据使用MSHFlexGrid控件获取并更新Excel中的数据要点:1、工程-引用,勾选Microsoft Excel 11.0 Object Libraly。
2、工程-部件,勾选Microsoft Hierarchical FlexGridControl 6.0。
3、在窗体添加一个MSHFlexGrid控件。
4、将需要打开更新的电子表格设置为“共享”(非常重要),方法:工具--共享工作簿。
代码:Private Sub Form_Load()Dim xlExcel As Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim AppExcel As ObjectSet xlExcel = CreateObject("Excel.Application")xlExcel.Workbooks.Open "C:\Program Files\Microsoft Visual Studio\mywork\book1.xls"Set xlBook = xlExcel.Workbooks("book1.xls")Set xlSheet = xlBook.Worksheets(2)'选择第2个工作表Dim i As LongWith xlSheetx = 2y = 1While .Cells(2, y).Value <> ""y = y + 1WendWhile .Cells(x, 1).Value <> ""x = x + 1Wend'Debug.Print .RowsMSHFlexGrid1.Rows = x - 1MSHFlexGrid1.Cols = y - 1 MSHFlexGrid1.TextMatrix(0, 0) = .Cells(2, 1).ValueFor j = 2 To MSHFlexGrid1.ColsDim k As Integerk = jIf k Mod 2 = 1 Then k = k - 1MSHFlexGrid1.TextMatrix(0, j - 1) = .Cells(1, k) & .Cells(2, j) NextFor i = 3 To MSHFlexGrid1.RowsFor j = 1 To MSHFlexGrid1.Cols MSHFlexGrid1.TextMatrix(i - 2, j - 1) = .Cells(i, j).ValueNextNextEnd WithWith MSHFlexGrid1.Col = 1.Row = 1' .CellBackColor = vbBlueEnd With xlBook.Close (False) '关闭EXCEL工作簿Set xlSheet = NothingSet xlBook = NothingxlExcel.Quit '关闭EXCELSet xlExcel = Nothing '释放EXCEL对象End SubPrivate Sub Command4_Click() Dim xlExcel AsExcel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim AppExcel As Object'MSFlexGrid1.Redraw = FalseSet xlExcel = CreateObject("Excel.Application")Set xlBook = xlExcel.Workbooks.Open("C:\Program Files\Microsoft Visual Studio\mywork\book1.xls", , ReadWrite) 'Set xlBook = xlExcel.Workbooks("zkb.xls")Set xlSheet = xlBook.Worksheets(2)' xlExcel.Visible = True '设置工作簿为可见With xlSheetFor i = 3 To MSHFlexGrid1.RowsFor j = 1 To MSHFlexGrid1.Cols .Cells(i, j) = MSHFlexGrid1.TextMatrix(i - 2, j - 1)NextNext End With'MSFlexGrid1.Redraw = TruexlBook.SavexlExcel.DisplayAlerts = FalsexlBook.Close (False) '关闭EXCEL工作簿Set xlSheet = NothingSet xlBook = NothingxlExcel.Quit '关闭EXCELSet xlExcel = Nothing '释放EXCEL对象End SubPrivate Sub Form_Load()Dim xlExcel As Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim AppExcel As ObjectSet xlExcel = CreateObject("Excel.Application")xlExcel.Workbooks.Open "C:\Program Files\Microsoft Visual Studio\mywork\book1.xls"Set xlBook = xlExcel.Workbooks("book1.xls")Set xlSheet = xlBook.Worksheets(2)Dim i As LongWith xlSheetx = 2y = 1While .Cells(2, y).Value <> ""y = y + 1WendWhile .Cells(x, 1).Value <> ""x = x + 1Wend'Debug.Print .RowsMSHFlexGrid1.Rows = x - 1MSHFlexGrid1.Cols = y - 1 MSHFlexGrid1.TextMatrix(0, 0) = .Cells(2, 1).ValueFor j = 2 To MSHFlexGrid1.ColsDim k As Integerk = jIf k Mod 2 = 1 Then k = k - 1MSHFlexGrid1.TextMatrix(0, j - 1) = .Cells(1, k) & .Cells(2, j) NextFor i = 3 To MSHFlexGrid1.RowsFor j = 1 To MSHFlexGrid1.Cols MSHFlexGrid1.TextMatrix(i - 2, j - 1) = .Cells(i, j).ValueNextNextEnd WithWith MSHFlexGrid1.Col = 1.Row = 1' .CellBackColor = vbBlueEnd With xlBook.Close (False) '关闭EXCEL工作簿Set xlSheet = NothingSet xlBook = NothingxlExcel.Quit '关闭EXCELSet xlExcel = Nothing '释放EXCEL对象End SubPrivate Sub MSHFlexGrid1_Click()With MSHFlexGrid1.CellBackColor = vbCyanText3 = .TextMatrix(.Row, .Col)End WithText3.SetFocusEnd SubPrivate Sub MSHFlexGrid1_DblClick()With MSHFlexGrid1If .CellBackColor = vbCyan Then .CellBackColor = &HFFFFFF End WithEnd Sub。
把WinForm的DataGridView的数据导出到Excel三种方法
把WinForm的DataGridView的数据导出到Excel三种方法导出WinForm的DataGridView数据到Excel有多种方法,下面将详细介绍三种常用的方法:方法一:使用Microsoft.Office.Interop.Excel库这是一种常用的方法,使用Microsoft.Office.Interop.Excel库可以直接操作Excel文件。
首先,需要在项目中添加对Microsoft Office 的引用。
然后,可以按照以下步骤导出数据:1. 创建一个Excel应用程序对象:```csharpusing Excel = Microsoft.Office.Interop.Excel;Excel.Application excelApp = new Excel.Application(;```2.创建一个工作簿对象:```csharpExcel.Workbook workbook =excelApp.Workbooks.Add(Type.Missing);```3.创建一个工作表对象:```csharpExcel.Worksheet worksheet = workbook.ActiveSheet;```4. 将DataGridView中的数据导入到Excel中:```csharpfor (int i = 0; i < dataGridView.Rows.Count; i++)for (int j = 0; j < dataGridView.Columns.Count; j++)worksheet.Cells[i + 1, j + 1] =dataGridView.Rows[i].Cells[j].Value.ToString(;}```5. 保存Excel文件并关闭Excel应用程序:```csharpworkbook.SaveAs("路径\\文件名.xlsx");excelApp.Quit(;```方法二:使用OpenXml库OpenXml是一种用于操作Office文件的开放式标准。
MSHflexGrid表格控件使用方法(1)
MSHflexGrid表格控件使用方法(1)2009-07-18 14:36下面我给大家讲一下MSHFLEXGRID常用的属性,方法事件,还有一些不能不知道的技巧.1) MSHFLEXGRID的重要属性.MSHFLEXGRID的属性非常多,其实绝大部分的属性和网格的显示的外观有关.在MSDN里,这些属性足以将人搞得眼花缭乱的了(我相信你没有耐性一个一个地翻查).下面列出常用的属性,方法事件及其简要说明.以便查阅.属性类型说明AllowBigSelector Boolean 返回/设置一个值,定义当在行或列的头部单击时,是否该行或列将整个被选中AllowUseResizing Enum 设置/返回一个值,定义用户是否可以调整网格行,列的尺寸BackColor Ole_Color 设置/返回一网格中非固定单元的背景色BackColorBand Array/Ole_Color 设置/返回网格中每个独立BAND的背景色BachColorBkg Ole_Color 设置/返回网格的背景色(单元头部除外) BackColorFixed Ole_Color 设置/返回网格中固定单元的背景色BackColorHeader Array/Ole_Color 设置/返回网格头部单元的背景色BackColorIndent Array/Ole_Color 设置/返回网格中凹痕部分的背景色BackColorSel Ole_Color 设置/返回网格选中单元的背景色BackColorUnpopulated Ole_Color 设置/返回网格非用户操作区的背景色BandData Array/Long 为独BAND设置/返回任意的值,以合在代码中通过这些值确定BANDBandDisplay Enum 定义在网格中BAND是水平还是垂直显示BandExpandable ARRAY/BOOLEN 设置/返回值指明独立的BAND能否被折叠或展开BandIndent Array/Long 定义BAND划分的字段数量BandLevel Long 返回当前的单元包含的BAND总数量Bands Long 返回网格中BAND总数量CellAlignment Integer 设置/返回一个值以定义当前单元的水平和垂直对齐方式CellBackColor Ole_Color 定义当前单元的字体是否为粗体CellFontBold Boolean 定义当前单元的字体是否为粗体CellFontItalic Boolean 定义当前单元的字体是否为斜体CellFontName String 定义当前单元的字体名CellFontSize String 定义当前单元的字体大小CellFontStrikeThough Boolean 定义当前单元的字体是否为突显示CellFontUnderline Boolean 定义当前单元的字体是有下划线CellFontWidth Single 定义当前单元的字体宽(用点表示)CellFontColor Ole_Color 设置/返回当前单元格的前景色CellHeight Long 设置/返回当前单元格的高度CellLeft Long 返回当前单元格的左边距CellPicture StdPicture 设置/返回当前单元格的图片CellPictureAlignment Integer 设置/返回当前单元格或某范围的单元格的图像对齐方式CelltextStyle Enum 设置/返回当前单元或选中范围单元文本的3D风格CellTop Long 返回当前单元格的垂直位置CellType Enum 设置/返回当前单元格的类型(标准.固定)CellWidth Long 返回/设置当前的单元的宽度Clip String 设置/返回网格选定范围单元的内容Col Array/Integer 设置/返回当前单元的水平坐标ColAlignment Array/Integer 设置/返回当前列的对齐方式ColalignmentBand Array/Integer 设置/返回BAND数据列的对齐方式ColAlignmentFixed Array/Integer 设置/返回固定单元数据的对齐方式ColAlignmentHeader Array/Integer 设置/返回固定头部单元数据的对齐方式ColData Ayyay/Long 为独立列设置/返回任意的值,以合在代码中通过这些值确定列ColHeader Array/Enum 定义每个BAND头部是否显示ColHeaderCaption Array/Single 定义每个BAND的列头部显示的文本ColIsVisible ARRAY/BOOLEN 返回/设置某个列是否可见ColPos Array/Long 返回某个给定列的左上角和网格左上角的距离Colposition Array/Long 设置网格列的位置Cols Long 返回/设置网格的列数量ColSel Array/Long 设置/返回某个范围单元的起始列ColWidth Array/Long 设置/返回某个列的宽度ColWordWrapOption Array/Integer 设置/返回网格的非固定单元是否允许WRAP ColWordWrapOptionBand Array/Integer 定义网格的BAND是否允许WRAP ColWordWrapOptionFixed Array/Integer 定义列的固定单元是否允许WRAP ColWordWrapOptionHeader Array/Integer 定义各头部是否允许WRAP DataField Array/Single 一个独立列绑定的数据库字段FillStyle Enum 定义改变文本或单元的其他属性是影响所有的选中单元还是只影响活动单元FixedCols Long 设置/返回固定列的列数FixedRows Long 设置/返回固定行的行数FocusRect Enum 定义控件对当前单元的焦点表示Font StdFont 返回/设置默认字体或各单元使用的字体FontBand Array/StdFont 设置/返回各BAND使用文本的字体FontFixed Single 设置/返回固定单元使用的字体FontHeader Array/StdFont 设置/返回各头部使用的字体FontWidth Single 设置/返回默认字体宽度FontWidthBand Array/Single 设置/返回BAND使用的字宽FontWidthFixed Single 设置/返回固定单元使用的字宽FontWidthHeader Array/Single 设置/返回每个头部使用的字宽ForeColr Ole_Color 设置/返回网格非固定单元使用的前景色ForeColorBand Array/Ole_Color 设置/返回网格各BAND的前景色ForeColorFixed Ole_Color 设置/返回网格固定单元的前景色.ForeColorHeader Array/Ole_Color 设置/返回网格头部单元的前景色ForeColorSel Ole_Color 设置/返回设置单元的前景色FormatString String 定义一个格式串用来设置网格列的宽度,对齐方式,固定行文本固定列文本GridColor Ole_Color 设置/返回网格单元间的线的颜色GridColorBand Array/Ole_Color 设置/返回网格BAND的线的颜色GridColorFixed Ole_Color 设置返回网格固定单元间的线的颜色GridColorHeader Array/Ole_Color 设置/返回网格头部间的线的颜色GridColorIndent Ole_Color 设置/返回网格INDENT单元间的线的颜色GridColorUnpopulated Ole_Color 设置/返回网格UNPOPULATED区域间的颜色GrigLine Enum 定义网格单元间的线的类型GrigLinesBand Array/Enum 定义网格各BAND间的线的类型GrigLinesFixed Enum 定义网格固定单元的线的类型GrigLinesHeader Array/Enum 定义网格各头部间的线的类型GrigLinesIndent Array/Enum 定义网格INDENT单元间的线的类型GrigLinesUnpopulated Enum 定义网格UNPOPULATED区域间的线的类型GrigLinesWidth Integer 设置/返回网格单元间的线的宽度GrigLinesWidthBand Array/Integer 设置/返回网格各BAND间的线的宽度GrigLinesWidthFixed Integer 设置/返回网格固定单元间的线的宽度GrigLinesWidthHeader Array/Integer 设置/返回网格各头间的线的宽度GrigLinesWidthIndent Array/Integer 设置/返回网格INDENT单元间的线的宽度GrigLinesWidthUnpopulated Integer 设置/返回网格UNPOPULATED区域间的宽度Hieght Enum 定义如何以及何时高亮度显示网格的选中单元LeftCol Long 网格最械的可见列MergeCells Enum 设置/返回一个值表明如何及何时将有相同内容的记录进行合并MergeCol ARRAY/BOOLEN 设置/返回一个值表明哪些列可以将内容合并MergeRow ARRAY/BOOLEN 设置/返回一个值表明哪些行可以将内容合并MouseCol Long 返回鼠标光标的列坐标位置MouseRow Long 返回鼠标光标的行坐标位置Picture StdPicture 返回MSHFLEXGRID的控件快照PictureType Enum 设置/返回PICTURE类型Redraw Boolean 设置/返回一个值,表明MSHFLEXGRIDR控件是否在每个改变后重画Row Long 设置/返回当前单元的垂直坐标RowData Array/Long 为各行设置/返回任意的值,以合在代码中通过这些值确定行RowExpandable Boolean 定义当前行是否可以展开RowExpanded Boolean 返回一个值表明当前行是否展开RowHeight Array/Long 设置/返回各行的高度RowHeightMin Long 设置/返回网格中行的最小高度RowIsVisible ARRAY/BOOLEN 设置/返回一个值,表明某个特定列是否可见RowPos Array/Long 返回给定行左上角和MSHFLEXGRID控件左上角的距离RowPosition Array/Long 设置某个网格行的位置Rows Long 返回网格的行的总数或者或BAND的行的总数RowSel Long 设置/返回一个范围的单元的起始行RowSizingMode Enum 设置/返回一个值表明对一行的设置是影响网格的所有行还是只影响被调整的行ScrollBars Enum 设置/返回一个值表明MSHFLEXGRID控件的滚动条类型ScrollTrack Boolean 设置/返回一个值表明网格内容是在用户移动滚动条时随着改变还是滚动结束后改变SelectionMode Enum 设置/返回一个值表明MFHFLEXGRID控件允许的选择类型. Sort Enum 根据某些村准备设置排序的值Text String 设置/返回一个单元或一个范围内单元的文本内容TextArray array/string 不改变ROW,COL属性,设置/返回任意单元的文本内容TextMatrix array/string 设置/返回某个选定行,列的单元的文本内容TextStyle Enum 设置/返回网格通常单元的3D文本风格TextStyleBand Array/Enum 设置/返回网格BAND的3D文本风格TextStyleFixed Enum 设置/返回网格各固定行的3D文本风格TextStyleHeader Array/Enum 设置/返回网格各头部的3D文本风格TopRow Long 设置/返回网格最上面的可见行Version Integer 返回正在使用MSHFLEXGRID控件的版本WordWrap Boolean 定义当到达单元的边界时,网格的单元的内容是否WRAP2) MSHFLEXGRID控件的重要方法方法说明AddItem 向网格中加入一新行Clear 清除网格中的内容ClearStructure 清除网格的结构(映射信息)CollapseAll 折叠网格的某个特定的所有行ExpandAll 展开网格的某个特定的所有行RemoveItem 从网格中清除一行方法AddItem和RemoveItem可以用来向网格中加入或删除行(BANDS).如果折叠或展开某个BAND的所有行,则可以使用COLLAPSEALL和EXPAANDALL方法.方法CLEAR可以清除网格中的内容,但不影响网格的行,列数,如果要清除网格的结构,包括顺序及网格各列的名称,应当使用ClearStructure方法.3) MSHFELXGRID的控件的主要事件Collapse 用户折叠了网格的一行Compare 当SORT属性被设置为CUSTOMERSORT,允许用户定义排序过程EnterCell 当一个新的单元成为当前活动单元时Expand 用户展开了网格的一行LeaveCell 当一个新单元成为当前活动单元前RowColChange 当一个新单元成为当前活动单元时Scroll 用户用键盘,滚动条滚动网格的内容或网格的内容由程序滚动时SelChangeEvent 一个新范围内的单元被选中EnterCell, LeaveCell, RowColChange事件相互联系,因为字们都在当一个新单元成为当前活动单元时被激发,实际上这些事件的顺序是:LeaveCell, EnterCell然后是RowColChange.Collapse和Expand事件在用户折叠或者展开网格的一行(BAND)时被激发.属性ROW和COL可以用来确定用户折叠或者展开的单元.当SORT属性设置为9时,对网格的每两行发生一次COMPARE事件,用户排序方法使你可以选择按照午任意列或单元对行排序.注意,使用这种排序方式的速度会慢于BUILD-IN排序.不论采用何种方式,只要对网格进行滚动时,SCROLL事件就会被激发.当SCROLLTRACK属性设置为TRUE时,如果用户用鼠标拖动或滚动时,该事件也被激发,如果SCROLLTRACK属性被设置为FALSE时,SCROLL事件只在拖动结束后激发一次.当选择单元格变化时, SelChangeEvent事件会被激发,对选择的单元范围的改变,可以通过用户操作或程序代码来实现.1) MSHFLEXGRID的编辑.关于MSHFLEXGRID的编辑,很多书都有介绍.一般都是用一个TEXTBOX作为的输入框,通过移动TEXTBOX来达到类似于EXCEL的编辑功能.很多书介绍的方法是在MOUSEDOWN或CLICK事件中移动TEXTBOX,然后,再在LeaveCell事件中写入. 本文的方法与其有类似之处,但亦有小许不同,主要在写入网格时,在TEXTBOX的Change事件中写入.2)网格内容的保存与加载对于网格的保存,一般人喜欢使用.Clip属性,将整个网格一次性地写入一个文件中,当然,在文件不大时,这当然是一个好办法.但是,当网格达到几千行几万行时,这个方法好象不是很好.(各位如果有兴趣的话,可以试试下面的程序)‘将网格设置成5000*12,然后用随机数填充网格.然后,调用下面程序Private Sub Command4_Click()Dim msgStr As StringDim FileID As LongDim T1 As DateDim T2 As DateT1 = Timer()With MSHFlexGrid1.Row = 0.Col = 0.RowSel = .Rows - 1.ColSel = .Cols - 1FileID = FreeFilemsgStr = .ClipOpen "C:\LX.TXT" For Output As #FileIDPrint #FileID, msgStrClose #FileIDEnd WithT2 = Timer()MsgBox T2 - T1End Sub反正我的感觉是:好象死机一般,要过一分多钟后计算机才能反应过来(实测是82.5秒左右,我的计算机是:AMD2500+,512M内存).为什么一次性的写入会如此的慢呢?这大概是有的人想不到的地方.其实,这跟VB处理字符串的机制有关,如果处理5K的字符串要一秒的话,那么,处理30K的字符串绝不是处理5K的6倍,而是长得多.这种关系几乎是呈某种几何级数的关系.明白了VB原来处理大字符串的效率原来是这么底.那么,解决的办法自然就有了.就是一个字:拆,将大拆小将会大大地加快处理字符串的速度.所以,下面的网格的保存函数的主要思想就将网格中的数据分步保存,每一次保存一小部分.直到整个网格保存完成.当然,其中还有一些细小的技巧,例如:保存时将先将网格中的行,列,固定行,固定列的总数保存,然后,保存各列的宽度,再然后正式保存数据.这都是为了加载的方便与快捷作了一定的处理.(参考下面的程序)Option ExplicitDim m_Row As LongDim m_Col As LongPrivate Sub Command3_Click()'填充网格Dim R As LongDim C As LongFor R = 0 To MSHFlexGrid1.Rows - 1For C = 0 To MSHFlexGrid1.Cols - 1MSHFlexGrid1.TextMatrix(R, C) = R & CNextNextEnd SubPrivate Sub Form_Load()With MSHFlexGrid1Text1.Visible = False.RowHeight(-1) = 285'设定网格是5000行.12列..Rows = 5000: .Cols = 12End WithEnd Sub'保存文件Private Sub Command1_Click()Call SaveFile(MSHFlexGrid1, "c:\kk.grd")End Sub'加载文件Private Sub Command2_Click()Call LoadFile(MSHFlexGrid1, "c:\kk.grd")End SubPrivate Sub MSHFlexGrid1_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)Text1.Visible = FalseWith MSHFlexGrid1m_Row = .MouseRowm_Col = .MouseColIf m_Row < .FixedRows Then m_Row = .FixedRowsIf m_Col < .FixedCols Then m_Col = .FixedCols.Row = m_Row: .Col = m_ColText1.Move .Left + .CellLeft, .Top+ .CellTop, .CellWidth, .CellHeightText1.Text = .TextText1.Visible = TrueText1.SetFocusEnd WithEnd SubPrivate Sub Text1_Change()With MSHFlexGrid1.TextMatrix(m_Row, m_Col) = Text1End WithEnd Sub'//**以下是相应的功能函数''加载一个文件到表格.'函数:LoadFileToGrid'参数:MsgObj Mshfelxgrid控件名,FileName 加载的文件名'返回值:=True 成功.=True 失败.Public Function LoadFile(MsgObj As Control, FileName As String) As Long Dim InputID As Long, FileID As LongDim EndRow As Long, DltAdd As LongDim AddFlag As BooleanDim KeyTab As String, KeyEnter As StringDim FixedRows As Long, FixedCols As LongDim GridInput As String, AddSum As String, RowColMax() As String Dim GridColMax As Long, GridRowMax As LongDim OleRow As Long, OleCol As LongDim SumFmtStr As StringDim DltCol As LongOn Error Resume NextWith MsgObj.Redraw = FalseErr.Clear: SetAttr FileName, 0If Err.Number <> 0 Then '如果文件不存在Err.ClearCall SaveFile(MsgObj, FileName).Redraw = TrueExit FunctionEnd IfKeyTab = Chr$(vbKeyTab): KeyEnter = Chr$(13)InputID = 0: AddSum = ""AddFlag = False: DltAdd = 25: DltCol = 1.Redraw = False: .FixedRows = 0: .FixedCols = 0FileID = FreeFileOpen FileName For Input As #FileIDDo While Not EOF(FileID) ' 循环至文件尾。
VB6[1].0_导出excel_方法源代码
往链点点通共享资源,了解更多请登录VB6.0 导出excel 方法源代码方法一:用Msflexgrid的Textmatrix属性取Msflexgrid中每一个单元格的内容,然后填到Excel表中,或者写成CSV格式方法二:直接把查询结果导出成Excel工作表Public Sub Export(formname As Form, flexgridname As String)Dim xlApp As Object 'Excel.ApplicationDim xlBook As Object 'Excel.WorkbookDim xlSheet As Object 'Excel.WorksheetScreen.MousePointer = vbHourglassOn Error GoTo Err_ProcSet xlApp = CreateObject("Excel.Application")Set xlBook = xlApp.Workbooks.AddSet xlSheet = xlBook.Worksheets(1)'Begin to fill data to sheetDim i As LongDim j As IntegerDim k As IntegerWith formname.Controls(flexgridname)For i = 0 To .rows - 1k = 0For j = 0 To .Cols - 1If .colwidth(j) > 20 Or .colwidth(j) < 0 Thenk = k + 1xlSheet.Cells(i + 1, k).Value = "'" & .TextMatrix(i, j)End IfNext jNext iEnd WithxlApp.Visible = TrueScreen.MousePointer = vbDefaultExit SubErr_Proc:Screen.MousePointer = vbDefaultMsgBox "请确认您的电脑已安装Excel!", vbExclamation,"提示"End Sub===================================Public Function ExporToExcel(strOpen As String)'*********************************************************'* 名称:ExporToExcel'* 功能:导出数据到EXCEL'* 用法:ExporToExcel(sql查询字符串)'*********************************************************Dim Rs_Data As New ADODB.RecordsetDim Irowcount As IntegerDim Icolcount As IntegerDim cn As New ADODB.ConnectionDim xlApp As New Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim xlQuery As Excel.QueryTableWith Rs_DataIf .State = adStateOpen Then.CloseEnd If.ActiveConnection = "provider=msdasql;DRIVER=Microsoft Visual FoxPro Dri ver;UID=;Deleted=yes;Null=no;Collate=Machine;BackgroundFetch=no;Exclusive=No;SourceType=DBF; SourceDB=D:\DBF;".CursorLocation = adUseClient.CursorType = adOpenStatic.Source = strOpen.OpenEnd WithWith Rs_DataIf .RecordCount < 1 ThenMsgBox ("没有记录!")Exit FunctionEnd If'记录总数Irowcount = .RecordCount'字段总数Icolcount = .Fields.CountEnd WithSet xlApp = CreateObject("Excel.Application")Set xlBook = NothingSet xlSheet = NothingSet xlBook = xlApp.Workbooks().AddSet xlSheet = xlBook.Worksheets("sheet1")xlApp.Visible = True'添加查询语句,导入EXCEL数据Set xlQuery = xlSheet.QueryTables.Add(Rs_Data, xlSheet.Range("a1"))xlQuery.FieldNames = True '显示字段名xlQuery.RefreshxlApp.Application.Visible = TrueSet xlApp = Nothing '"交还控制给ExcelSet xlBook = NothingSet xlSheet = NothingEnd Function=============================='*********************************************************'* 名称:OutDataToExcel'* 功能:将MsFlexGrid控件中显示的内容输出到Excel表格中进行打印'*********************************************************Public Sub OutDataToExcel(Flex As MSFlexGrid) '导出至ExcelDim s As StringDim i As IntegerDim j As IntegerDim k As IntegerOn Error GoTo ErtMe.MousePointer = 11Dim Excelapp As Excel.ApplicationSet Excelapp = New Excel.ApplicationOn Error Resume NextDoEventsExcelapp.SheetsInNewWorkbook = 1Excelapp.Workbooks.AddExcelapp.ActiveSheet.Cells(1, 3) = sExcelapp.Range("C1").SelectExcelapp.Selection.Font.FontStyle = "Bold"Excelapp.Selection.Font.Size = 16With Flexk = .RowsFor i = 0 To k - 1For j = 0 To .Cols - 1DoEventsExcelapp.ActiveSheet.Cells(3 + i, j + 1) = "'" & .TextMatrix(i, j)Next jNext iEnd WithMe.MousePointer = 0Excelapp.Visible = TrueExcelapp.Sheets.PrintPreviewErt:If Not (Excelapp Is Nothing) ThenExcelapp.QuitEnd IfEnd Sub一个按钮,点击出现对话框(对话框控件已经有),在硬盘里面查找excel文件(当然,后缀名是xls了),找到目标excel文件后,该excel文件里面是一些数据,点击确定,就可以把excel里面的内容保存到MSFlexGrid控件里面了还有一个,按钮,点击后出现对话框,可以保存MSFlexGrid里面的东西到一个excel里面谢谢大家了用CommonDialog可以解决选定打开.xls文件问题然后就是读取进去哈哈保存代码如下'添加command控件一个MSFlexGrid控件一个Private Sub Command1_Click()On Error Resume NextDim fileadd As StringCommonDialog1.ShowOpenCommonDialog1.Filter = "xls文件(*.xls)|*.xls" '选择你要的文件fileadd = CommonDialog1.FileNameMSHFlexGrid1.Redraw = False '关闭表格重画,加快运行速度Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象Set xlBook = xlApp.Workbooks.Open(fileadd) '打开已经存在的EXCEL工件簿文件xlApp.Visible = True '设置EXCEL对象可见(或不可见)Set xlsheet = xlBook.Worksheets("Sheet1") '设置活动工作表For R = 0 To MSHFlexGrid1.Rows - 1 '行循环For C = 0 To MSHFlexGrid1.Cols - 1 '列循环MSHFlexGrid1.Row = RMSHFlexGrid1.Col = CxlBook.Worksheets("Sheet1").Cells(R + 1, C + 1) = MSHFlexGrid1.Text '保存到EXCEL Next CNext RMSHFlexGrid1.Redraw = TruexlApp.DisplayAlerts = False '不进行安全提示'Set xlsheet = Nothing'Set xlBook = Nothing'xlApp.Quit'Set xlApp = Nothing。
vsFlexGrid常用功能介绍
vsFlexGrid是ComponentOne公司的一个ActiveX控件,它与MS的MSHFlexGrid控件在功能上是兼容的,即MSHFlexGrid所具备的属性和方法,它也都具备,只有少数几个属性名称略有不同,使用MSHFlexGrid编写的程序,只需要作较小的调整就可以转换过来;但相比MSHFlexGrid,vsFlexGrid多了很多功能,它的属性和事件非常丰富,可以实现非常灵活的控制和快捷的编码,下面主要对一些常用和实用的功能进行介绍:一、数据批量操作l 利用Cell属性批量存取数据比如要清除一块区域的文本,或者设置一块区域的字体,不用循环处理,只需要一条语句就可以完成,如:(flexcpText,1,1,5,5) = “” ‘设置(1,1)-(5,5)这块单元格区域的文本都为空(flexcpFontBold,1,1,5,5)=True ‘设置(1,1)-(5,5)这块单元格区域的字体都为粗体类似还可以设置的有单元格对齐、图片、颜色等。
而语句:strText = (flexcpText,1,1,5,5)返回一个用vbTab间隔列,vbCr间隔行的字符串,当然也可以反过来赋值,这样该区域内的每个单元格都可以赋不同的值。
l 使用-1对所有行列进行处理RowHeight(-1)=300 ‘将所有行的高度设置为300Twip,可以类似使用的属性有:RowHidden,ColWidth,ColHidden,ColAlignment等二、大量数据存放vsFlexGrid可以存放数据的地方有:CellText,CellData,ColData,RowData除了CellText是String类型外,其他都是Variant类型,也就是说你可以将任意类型的数据存放在表格中,比如日期(Date),类型变量(Type),集合(Collection),数组,记录集(RecordSet),以及各种对象(Object),这对于关联数据比较多的程序非常有用。
vsFlexGrid常用功能介绍
BeforeRowColChange(ByVal OldRow As Long, ByVal OldCol As Long, ByVal NewRow As Long, ByVal NewCol As Long, Cancel As Boolean)
BeforeScroll(ByVal OldTopRow As Long, ByVal OldLeftCol As Long, ByVal NewTopRow As Long, ByVal NewLeftCol As Long, Cancel As Boolean)
VSFlexGrid.CellBorderColorAs OLE_COLOR,LeftAs Integer,TopAs Integer,RightAs Integer,BottomAs Integer,VerticalAs Integer,HorizontalAs Integer
2)自动行高,列宽
使用AutoSize方法,可以使列宽、或者行高根据单元格的内容进行自适应调整。
5)背景
可以为vsFlexGrid设置背景图,背景图相对单元格式内容是透明的,并且可以设置对齐和平铺属性。
6)列排序,行、列拖动
设置vsFlexGrid.ExplorerBar属性,就可以实现类似Windows的资源管理器一样,点击列头进行列数据排序,或者用鼠标拖动改变列、行的顺序。
vsFlexGrid常用功能介绍
vsFlexGrid常用功能介绍vsFlexGrid是ComponentOne公司的一个ActiveX控件,它与MS的MSHFlexGrid控件在功能上是兼容的,即MSHFlexGrid所具备的属性和方法,它也都具备,只有少数几个属性名称略有不同,使用MSHFlexGrid编写的程序,只需要作较小的调整就可以转换过来;但相比MSHFlexGrid,vsFlexGrid多了很多功能,它的属性和事件非常丰富,可以实现非常灵活的控制和快捷的编码,下面主要对一些常用和实用的功能进行介绍:一、数据批量操作l 利用Cell属性批量存取数据比如要清除一块区域的文本,或者设置一块区域的字体,不用循环处理,只需要一条语句就可以完成,如:vsFlexGrid.Cell(flexcpText,1,1,5,5) = “” ‘设置(1,1)-(5,5)这块单元格区域的文本都为空vsFlexGrid.Cell(flexcpFontBold,1,1,5,5)=True ‘设置(1,1)-(5,5)这块单元格区域的字体都为粗体类似还可以设置的有单元格对齐、图片、颜色等。
而语句:strText = vsFlexGrid.Cell(flexcpText,1,1,5,5)返回一个用vbTab间隔列,vbCr间隔行的字符串,当然也可以反过来赋值,这样该区域内的每个单元格都可以赋不同的值。
l 使用-1对所有行列进行处理RowHeight(-1)=300 ‘将所有行的高度设置为300Twip,可以类似使用的属性有:RowHidden,ColWidth,ColHidden,ColAlignment等二、大量数据存放vsFlexGrid可以存放数据的地方有:CellText,CellData,ColData,RowData除了CellText是String类型外,其他都是Variant类型,也就是说你可以将任意类型的数据存放在表格中,比如日期(Date),类型变量(Type),集合(Collection),数组,记录集(RecordSet),以及各种对象(Object),这对于关联数据比较多的程序非常有用。
导出Excel的四种方法
/// </summary>
public string OutFilePath
{
set
{
outFilePath=value;
}
get
{
return outFilePath;
}
}
/**//// <summary>
///输入文件ቤተ መጻሕፍቲ ባይዱ径
/// </summary>
private string InputFilePath
//
// }
#endregion
公共方法#region公共方法
/**///
public void CreateExcel()
{
int rowIndex=4;//行起始坐标
int colIndex=1;//列起始坐标
ApplicationClass myApp=null;
Workbook myBook=null;
mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
DBGridEh导入到Excel
-----------------------------------------HmExcel.pas-----------------------------------------Delphi中DBGridEh导出数据到Excel中,支持多级(最多三级)层级列标题、支持页脚汇总栏导出。
日期、数字等形式的字符串类型自动使用Text格式,保持原有数据类型,防止Excel自作多情删除数字前导0,或将“-”、识别为日期等。
用法:将HmExcel.pas放置在Delphi的搜索路径下,或程序路径下添加该单元到工程中,然后Use该单元,或者直接将HmExcel添加到uses中。
然后就可以使用ExpToExcel 函数了。
unit HmExcel;interfaceusesForms,ComObj,DBGridEh,SysUtils,DB,Variants;function ExpToExcel(dbg:TDBGridEh;title:string;subTitle:string=''):Boolean;implementation{编写:HanMon 2006-07-10 最后修改:2012-09-11功能:DBGridEh导出到Excel,支持多表头合并(最多三列),合计栏导出声明:Procedure ExpToExcel(dbg:TDBGridEh;title:string;subTitle:string='');参数:1.dbg :控件,三方控件EhLib控件包中DBGridEh控件实例2.title :字符,导出Excel的第一行,默认字体24号3.subTitle :字符:子标题,默认为当前日期,可以传入导出的时间段注意:1.只支持最多三层标题的合并(多了也是浪费)2.多层标题中如(ABC|A,ABC,ABC|C)在表格中支持合并,即第二行第二列为空ABCA, ,C由于没有实际意义,本单元不支持,只支持如(ABC|A,ABC|B,ABC|C)严格以分割符'|'来识别3.如果有Footer,本单元只支持一行Footer导出}// 01.将数字列转换为Excel格式的字母列function getXlsCol(const col:integer):string;varm,n:integer;beginif (col<=0)or(col>256) thenresult:='Error'//异常(Error)else if col<=26 then beginm:=col+64;result:=chr(m);end else beginm:=(col-1)div 26;n:=col-26*m+64;result:=getXlsCol(m)+chr(n);end;end;{-------------------------------------------------}// 02.获得分层标题的层次数function getLevel(aTitle:string):integer;vari:integer;beginResult:=1;for i:=1 to length(aTitle) doif aTitle[i]='|' thenResult:=Result+1;end;{-------------------------------------------------}// 03.获得分层标题的最大层次function getMaxLevel(dbg:TDBGridEh):integer;varm,i:integer;beginResult:=1;for i:=0 to dbg.Columns.Count-1 do beginm:=getLevel(dbg.Columns[i].Title.Caption);if m>Result thenResult:=m;end;end;{-------------------------------------------------}// 04.获得同一层的结束位置(level=1顶层level=2次顶层)procedure getBeginEndCol(dbg:TDBGridEh;start,level:integer;var c1,c2:integer); vars,s1:string;beginc1:=start;c2:=start;s:=dbg.Columns[start].Title.Caption;if level=1 then beginif pos('|',s)=0 thenexit;s:=copy(s,1,pos('|',s))end else if level=2 then begins1:=copy(s,1,pos('|',s));s:=copy(s,pos('|',s)+1,maxInt);if pos('|',s)=0 thenexit;s:=s1+copy(s,1,pos('|',s));end;while (c1>=0)and(pos(s,dbg.Columns[c1].Title.Caption)>0) doc1:=c1-1;c1:=c1+1;while (c2<=(dbg.Columns.Count-1))and(pos(s,dbg.Columns[c2].Title.Caption)>0) do c2:=c2+1;c2:=c2-1;end;{-------------------------------------------------}// A.导出到Excel:参数1:第三方控件表格,参数2:标题,参数3:副标题function ExpToExcel(dbg:TDBGridEh;title:string;subTitle:string=''):Boolean;vari,j,k,col,maxLevel:integer;app,bok,sht:variant;s,s1:string;beginResult:=False;trytryapp:=getActiveOleObject('excel.application');exceptapp:=createOleObject('excel.application');end;exceptexit;end;trybok:=app.workbooks.add;sht:=app.worksheets[1];col:=dbg.Columns.Count;sht.cells(1,1):=title;if subTitle='' thensubTitle:=FormatDateTime('yyyy-mm-dd',date);sht.cells(2,1):=subTitle;// 可转换成数字或日期时间的字符串,Excel会自动转换成对应数据类型,可牵制设置成文本方式显示for i:=0 to dbg.Columns.Count-1 doif dbg.Columns[i].Field.DataType in [ftString,ftMemo,ftFixedChar,ftWideString,ftFmtMemo] then beginsht.range[format('%s:%s',[getXlsCol(i+1),getXlsCol(i+1)])].NumberFormatLocal:='@';end;//在Excel获得和分层表格相同的单元格合并// 例: ID AB|A AB|B CDE|CD|C CDE|CD|D CDE|E FmaxLevel:=getmaxLevel(dbg);for i:=0 to dbg.Columns.Count-1 do begin//所有数字以字符表示,可以调整为某部分列数字以文本表示s:=dbg.Columns[i].Title.Caption;//单层垂直合并if pos('|',s)=0 then beginsht.cells(3,i+1):=s;if maxLevel>1 thensht.range[format('%s3:%s%d',[getXlsCol(i+1),getXlsCol(i+1),maxLevel+2])].merge;continue;end elses1:=copy(s,1,pos('|',s)-1);s:=copy(s,pos('|',s)+1,maxInt);getBeginEndCol(dbg,i,1,j,k);//第三行合并if i=j then beginsht.cells(3,i+1):=s1;if j<>k thensht.range[format('%s3:%s3', [getXlsCol(j+1),getXlsCol(k+1)])].merge;end;//双层垂直合并if pos('|',s)=0 then beginsht.cells(4,i+1):=s;if maxLevel>2 thensht.range[format('%s4:%s%d',[getXlsCol(i+1),getXlsCol(i+1),maxLevel+2])].merge;continue;end;//三层getBeginEndCol(dbg,i,2,j,k);if i=j then beginsht.cells(4,i+1):=copy(s,1,pos('|',s)-1);if j<>k thensht.range[format('%s4:%s4', [getXlsCol(j+1),getXlsCol(k+1)])].merge;end;sht.cells(5,i+1):=copy(s,pos('|',s)+1,maxInt);end;//导出数据dbg.DataSource.DataSet.First;i:=2+MaxLevel;while not dbg.DataSource.DataSet.Eof do begini:=i+1;sht.cells(i,1):=i-3;for j:=0 to col-1 doif dbg.Columns[j].Field<>nil then //忽略不与数据库字段对应的列sht.cells(i,j+1):=dbg.Columns[j].Field.DisplayText;dbg.DataSource.DataSet.Next;end;dbg.DataSource.DataSet.First;//导出页脚统计数据数据if dbg.FooterRowCount>0 then begini:=i+1;for j:=0 to col-1 doif dbg.Columns[j].Footer.ValueType=fvtStaticText thensht.cells(i,j+1):=dbg.Columns[j].Footer.Valueelse if dbg.Columns[j].Footer.ValueType=fvtNon thencontinueelsesht.cells(i,j+1):=varToStr(dbg.Columns[j].Footer.SumValue);end;//设置Excel格式s:=format('A1:%s1', [getXlsCol(col)]); //主标题(第一行)sht.range[s].merge;sht.range[s].font.size:=14;s:=format('A2:%s2',[getXlsCol(col)]); //副标题(第二行)sht.range[s].merge;sht.range[s].font.size:=10;s:=format('A1:%s%d',[getXlsCol(col),2+MaxLevel]); //主标题,副标题,列名(前三行)水平垂直居中,粗体sht.range[s].HorizontalAlignment:=-4108;sht.range[s].VerticalAlignment:=-4108;sht.range[s].font.bold:=true;if dbg.FooterRowCount>0 then //列名,数据区加边框(不包括页脚区)sht.range[format('A3:%s%d',[getXlsCol(col),i-1])].borders.lineStyle:=1 elsesht.range[format('A3:%s%d',[getXlsCol(col),i])].borders.lineStyle:=1;s:=format('A3:%s%d',[getXlsCol(col),i]); //列名,数据,统计行字体10,自动换行,加边框sht.range[s].font.size:=10;sht.columns[format('A:%s',[getXlsCol(col)])].EntireColumn.AutoFit; //自动适应列宽bok.saved:=true;app.visible:=true;excepton e:Exception do beginApplication.MessageBox(PChar(e.Message+#13+' 数据导出异常,操作取消!'),'提示');bok.saved:=true;app.quit;end;end;sht:=unAssigned;bok:=unAssigned;app:=unAssigned;Result:=True;end;end.。
C#利用Microsoft.Office.Interop.Excel导出数据到Excel
C#利⽤Microsoft.Office.Interop.Excel导出数据到Excel添加引⽤(VS2013位于C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15⽂件夹下)本案例是直接将DataTable⾥⾯的数据导⼊到Excel内,所以需将数据转换成DataTable数据类型才可以using Microsoft.Office.Interop.Excel;using System.Reflection;public void DataTableToExcel(System.Data.DataTable dataTable, string strTitle, string[] strHead, int[] columnWidth){int nMax = dataTable.Rows.Count;int nMin = 0;int rowCount = nMax - nMin + 1;//总⾏数const int columnCount = 7;//总列数//创建Excel对象Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();//新建⼯作簿Workbook workBook = excelApp.Workbooks.Add(true);//新建⼯作表Worksheet worksheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;////设置标题Microsoft.Office.Interop.Excel.Range titleRange = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]];//选取单元格titleRange.Merge(true); //合并单元格titleRange.Value2 = strTitle; //设置单元格内⽂本 = "微软雅⿊"; //设置字体titleRange.Font.Size = 18; //字体⼤⼩titleRange.Font.Bold = true; //加粗显⽰titleRange.HorizontalAlignment = XlHAlign.xlHAlignCenter; //⽔平居中titleRange.VerticalAlignment = XlVAlign.xlVAlignCenter; //垂直居中titleRange.Borders.LineStyle = XlLineStyle.xlContinuous; //设置边框titleRange.Borders.Weight = XlBorderWeight.xlThin; //边框常规粗细//设置表头//string[] strHead = new string[columnCount] { "id", "productUid", "productBarcode", "checkData", "checkResult", "creater", "checkDate" };//int[] columnWidth = new int[columnCount] { 8, 24, 24, 22, 10, 14, 20 };for (int i = 0; i < columnCount; i++){Microsoft.Office.Interop.Excel.Range headRange = worksheet.Cells[2, i + 1] as Microsoft.Office.Interop.Excel.Range;//获取表头单元格,不⽤标题则从1开始headRange.Value2 = strHead[i]; //设置单元格⽂本 = "Consolas"; //设置字体headRange.Font.Size = 13; //字体⼤⼩headRange.Font.Bold = true; //加粗显⽰headRange.HorizontalAlignment = XlHAlign.xlHAlignCenter; //⽔平居中headRange.VerticalAlignment = XlVAlign.xlVAlignCenter; //垂直居中headRange.ColumnWidth = columnWidth[i]; //设置列宽headRange.Borders.LineStyle = XlLineStyle.xlContinuous; //设置边框headRange.Borders.Weight = XlBorderWeight.xlThin; //边框常规粗细}//设置每列格式for (int i = 0; i < columnCount; i++){Microsoft.Office.Interop.Excel.Range contentRange = worksheet.Range[worksheet.Cells[2, i + 1], worksheet.Cells[rowCount - 1 + 3, i + 1]];//不⽤标题则从第⼆⾏开始 = "Consolas";contentRange.Font.Size = 10;contentRange.HorizontalAlignment = XlHAlign.xlHAlignCenter; //⽔平居中contentRange.VerticalAlignment = XlVAlign.xlVAlignCenter; //垂直居中contentRange.Borders.LineStyle = XlLineStyle.xlContinuous; //设置边框contentRange.Borders.Weight = XlBorderWeight.xlThin; //边框常规粗细contentRange.WrapText = true; //⾃动换⾏contentRange.NumberFormatLocal = "@"; //⽂本格式}//填充数据for (int i = 0; i < dataTable.Rows.Count; i++){DataRow row = dataTable.Rows[i];for (int j = 0; j < dataTable.Columns.Count; j++){excelApp.Cells[i + 3, j + 1] = row[j].ToString();}}//设置Excel可见excelApp.Visible = true;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
如何把MSHFlexGrid里的数据导出至Excel?用Adodc1做了查询语句,结果显示在一个MSHFlexGrid里面。
现在要求做一个按钮(Command1),点击它就把MSHFlexGrid里显示的数据导出至Excel表中。
就是一点这个按钮,就会自动打开Excel,然后数据就已经进去了,方便编辑和打印。
要求:代码详细,直接复制到Command1下就能用。
这块我不懂,所以不要搞什么子程序调用之类的,要有子程序也给直接调用好。
直接复制代码成功后,再追加100分。
把这个弄完工程就结了,再不用受罪了,哈哈!以下是精简后的代码,不清楚你工作中的一些细节,所以如有问题与我讨论Private Sub Command1_Click()MSFlexGrid1.Redraw = False '关闭表格重画,加快运行速度Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象Set xlBook = xlApp.Workbooks.Open(App.Path & "\对账模板.xls") '打开已经存在的EXCEL 工件簿文件xlApp.Visible = True '设置EXCEL对象可见(或不可见)Set xlsheet = xlBook.Worksheets("Sheet1") '设置活动工作表For R = 0 To MSFlexGrid1.Rows - 1 '行循环For C = 0 To MSFlexGrid1.Cols - 1 '列循环MSFlexGrid1.Row = RMSFlexGrid1.Col = CxlBook.Worksheets("Sheet1").Cells(R + 1, C + 1) = MSFlexGrid1.Text '保存到EXCEL Next CNext RMSFlexGrid1.Redraw = True'xlsheet.PrintOut '打印工作表xlApp.DisplayAlerts = False '不进行安全提示'xlBook.Close (False) '关闭工作簿Set xlsheet = NothingSet xlBook = NothingxlApp.QuitSet xlApp = NothingEnd Sub下面的代码就也能导出到EXCELDim xlApp As Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim i As Long, J As LongOn Error GoTo ErrorHandleSet xlApp = CreateObject( "Excel.Application ")Set xlBook = xlApp.Workbooks.AddSet xlSheet = xlBook.Worksheets(1)For i = 0 To MHFGrid.Rows - 1For J = 0 To MHFGrid.Cols - 1xlSheet.Cells(i + 1, J + 1).Value = MHFGrid.TextMatrix(i, J)Next JNext ixlSheet.Application.Visible = TrueSet xlSheet = NothingSet xlBook = NothingSet xlApp = NothingExit SubErrorHandle:MsgBox "错误:" & Err.Number & vbCrLf & Err.Description, vbOKOnly, "运行错误"如何将表中的数据导出到电子表格中作者:施进兵有很多方法都可将数据库中某个表的数据导出到电子表格中,例如通过创建Access.Application,可以利用Access本身的导出功能实现将表中的数据导出到电子表格中。
但是这种方法会占用较多的系统资源,并且缺乏通用性。
如果一个数据库没有导出的功能怎么办?下面的这段程序代码利用记录集实现导出的功能,这种做法的好处是显而易见的:你可以控制要导出的数据,而不用将整个表的内容都导出到电子表格中。
为简单起见下面的程序代码仍将整个表的数据导出到电子表格中。
如果你有兴趣的话,对下面的代码稍加改动就可做成更为通用的一个类或是一个控件。
首先在窗体上添加一个标签控件和一个命令按钮,然后在工程中添加对DAO引用。
利用下面的程序代码就可将表中的数据导出到电子表格中。
Option ExplicitPrivate Sub Command1_Click()Dim tempDB As DatabaseDim i As Integer ' 循环计数器Dim j As IntegerDim rCount As Long ' 记录的个数Dim xl As Object ' OLE自动化对象Dim Sn As RecordsetScreen.MousePointer = 11Label1.Caption = "打开数据库... "Label1.RefreshSet tempDB = Workspaces(0).OpenDatabase( "Nwind.mdb ")Label1.Caption = "创建Excel对象... "Label1.RefreshSet xl = CreateObject( "Excel.Sheet.8 ")Label1.Caption = "创建快照型记录集... "Label1.RefreshSet Sn = tempDB.OpenRecordset( "Customers ", dbOpenSnapshot)If Sn.RecordCount > 0 ThenLabel1.Caption = "将字段名添加到电子表格中"Label1.RefreshFor i = 0 To Sn.Fields.Count - 1xl.Worksheets(1).cells(1, i + 1).Value = Sn(i).NameNextSn.MoveLastSn.MoveFirstrCount = Sn.RecordCount' 在记录中循环i = 0Do While Not Sn.EOFLabel1.Caption = "Record: " & Str(i + 1) & " of " & _Str(rCount)Label1.Refresh' 加每个字段的值加到工作表中If Sn(j).Type < 11 Thenxl.Worksheets(1).cells(i + 2, j + 1).Value = Sn(j)Else' 处理Memo和LongBinary 类型的字段xl.Worksheets(1).cells(i + 2, j + 1).Value = "Memo or Binary Data "End IfNext jSn.MoveNexti = i + 1Loop' 保存工作表Label1.Caption = "保存文件... "Label1.Refreshxl.SaveAs "c:\Customers.XLS "'从内存中删除Excel对象Label1.Caption = "退出Excel "Label1.Refreshxl.Application.QuitElse' 没有记录End If' 清除Label1.Caption = "清除对象"Label1.RefreshSet xl = NothingSet Sn = NothingSet tempDB = NothingScreen.MousePointer = 0 ' 恢复鼠标指针Label1.Caption = "Ready "Label1.RefreshEnd SubPrivate Sub Form_Load()Label1.AutoSize = TrueLabel1.Caption = "Ready "Label1.RefreshEnd Sub给你个我用的方法,很好用'Option Explicit''*********************************************************''* 名称:ExportToExcel''* 功能:导出数据到EXCEL''* 用法:ExporToExcel 记录集,标题''*********************************************************'Public Function ExportToExcel(Rs_Data As ADODB.Recordset, CenterHeader As String) As Boolean ' Dim Irowcount As Integer' Dim Icolcount As Integer' Dim SA As String' Dim xlApp As New Excel.Application' Dim xlBook As Excel.Workbook' Dim xlSheet As Excel.Worksheet' Dim xlQuery As Excel.QueryTable'On Error GoTo err' With Rs_Data' If .state = adStateOpen Then' .Close' End If' .ActiveConnection = DBConn' .CursorLocation = adUseClient' .CursorType = adOpenStatic' .LockType = adLockReadOnly' '.Source = strOpen' .Open' End With' With Rs_Data' '记录总数' Irowcount = .RecordCount' '字段总数' Icolcount = .Fields.Count' End With' Set xlApp = CreateObject("Excel.Application")' Set xlBook = Nothing' Set xlSheet = Nothing' Set xlBook = xlApp.Workbooks().add' Set xlSheet = xlBook.Worksheets("sheet1")' xlApp.Visible = False' '添加查询语句,导入EXCEL数据' Set xlQuery = xlSheet.QueryTables.add(Rs_Data, xlSheet.Range("a1"))' With xlQuery' .FieldNames = True' .RowNumbers = False' .FillAdjacentFormulas = False' .RefreshOnFileOpen = False' .BackgroundQuery = True' .RefreshStyle = xlInsertDeleteCells' .SavePassword = True' .SaveData = True' .AdjustColumnWidth = True' .RefreshPeriod = 0' .PreserveColumnInfo = True' End With' xlQuery.FieldNames = True '显示字段名' xlQuery.Refresh' If CenterHeader = "开停历史纪录" Then' SA = "A1:H" + CStr(Irowcount + 1)' ElseIf CenterHeader = "锁闭阀运行状态" Then' SA = "A1:F" + CStr(Irowcount + 1)' ElseIf CenterHeader = "锁闭阀分配表" Then' SA = "A1:F" + CStr(Irowcount + 1)' ElseIf CenterHeader = "用户信息汇总" Then' SA = "A1:I" + CStr(Irowcount + 1)' ElseIf CenterHeader = "锁闭阀开停设置" Then' SA = "A1:H" + CStr(Irowcount + 1)' ElseIf CenterHeader = "房间信息" Then' SA = "A1:J" + CStr(Irowcount + 1)' End If' With xlSheet' '.Range(.Cells(1, 1), .Cells(1, Icolcount)) = "宋体"' '.Range(.Cells(1, 1), .Cells(1, Icolcount)).Font.Size = 10' '标题字体加粗' '.Range(.Cells(1, 1), .Cells(Irowcount + 1, Icolcount)).Borders.LineStyle = xlContinuous ' '设表格边框样式'字体' .Range(SA) = "宋体"' .Range(SA).Font.Size = 10' '设标题为黑体字' .Range(.Cells(1, 1), .Cells(1, Icolcount)).Font.Bold = True'列宽度' If CenterHeader = "开停历史纪录" Then' .Columns("A:A").ColumnWidth = 8.63' .Columns("B:B").ColumnWidth = 11.38' .Columns("C:C").ColumnWidth = 12.63' .Columns("D:D").ColumnWidth = 6.75' .Columns("E:E").ColumnWidth = 13.31' .Columns("F:F").ColumnWidth = 7' .Columns("G:G").ColumnWidth = 7' .Columns("H:H").ColumnWidth = 7.63' '对齐' .Range(SA).HorizontalAlignment = xlCenter' .Range(SA).VerticalAlignment = xlCenter' '边框' .Range(SA).Borders(xlDiagonalDown).LineStyle = xlNone' .Range(SA).Borders(xlDiagonalUp).LineStyle = xlNone' With .Range(SA).Borders(xlEdgeLeft)' .LineStyle = xlContinuous' .Weight = xlThin' .ColorIndex = xlAutomatic' End With' With .Range(SA).Borders(xlEdgeTop)' .LineStyle = xlContinuous' .Weight = xlThin' .ColorIndex = xlAutomatic' End With' With .Range(SA).Borders(xlEdgeBottom)' .LineStyle = xlContinuous' .Weight = xlThin' .ColorIndex = xlAutomatic' End With' With .Range(SA).Borders(xlEdgeRight)' .LineStyle = xlContinuous' .Weight = xlThin' .ColorIndex = xlAutomatic' End With' With .Range(SA).Borders(xlInsideVertical)' .LineStyle = xlContinuous' .Weight = xlThin' .ColorIndex = xlAutomatic' End With' With .Range(SA).Borders(xlInsideHorizontal)' .LineStyle = xlContinuous' .Weight = xlThin' .ColorIndex = xlAutomatic' End With' End With' '页面设置' With xlSheet.PageSetup' .LeftHeader = "" & "" & Chr(10) & "&10 单位名称:"' .CenterHeader = "&""宋体,加粗""&16" & CenterHeader' .RightHeader = "&""Times New Roman,常规""&10" & "" & Chr(10) & "&""宋体,常规""打印日期&""Times New Roman,常规"":&D "' .LeftFooter = ""' .CenterFooter = "第&P 页,共&N 页"' .PrintHeadings = False' .PrintGridlines = True' .PrintComments = xlPrintNoComments' '.PrintQuality = 200' .CenterHorizontally = False' .CenterVertically = False' .Draft = False' .PaperSize = xlPaperA4' .FirstPageNumber = xlAutomatic' .Order = xlDownThenOver' .BlackAndWhite = False' .Zoom = 100' End With' xlApp.Application.Visible = True' '交还控制给Excel' Set xlApp = Nothing '' Set xlBook = Nothing' Set xlSheet = Nothing' Exit Function'err:' MsgBox err.Description, vbInformation, MsgTitle 'End Function[VB]将VB表格中的数据导出到Excel(2006-5-14 17:30:00)【收藏】【评论】【打印】【关闭】步骤介绍:首先在VB建一个MSFlexGrid表格,再连接到数据库,将数据库的表的资料显示到表格中,最后调用ExportExcel1()函数将表格中数据导出到Excel.第一步:在VB建一个MSFlexGrid表格,再连接到数据库,将数据库的表的资料显示到表格中,这个代码我就不写了。