数据库查询到一个Excel文件

我在这里有一个在VB.NET的代码。 该代码使程序能够从MS ACCESS database进行查询并将其保存到Excel File(.xls)并提示用户是否要打开该文件。 代码工作正常,但我有一个问题,当文件已被打开。 列没有自动适合其内容,使文件如此混乱,我也想让用户有一个选项来打印文件。 有什么办法可以解决我的问题吗? 如果您有任何澄清,请随时询问。

 If (Not Directory.Exists("C:\Sales Monitoring Report")) Then Directory.CreateDirectory("C:\Sales Monitoring Report") End If System.IO.File.Delete("C:\Sales Monitoring Report\Transaction.xls") Dim createExcelFile = "SELECT ORNumber, UserID, TransactionID, Vatable, Tax, Amount, TransactionDate, Status INTO [Excel 12.0;HDR=YES;DATABASE=C:\Sales Monitoring Report\Transaction.xls].[Sheet1] FROM tbl_transaction" ExecNonQuery(createExcelFile) If MessageBox.Show("Do you want to open the file?", "Open File", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then Dim excelFile As New Excel.Application Dim excelWorkBook As Excel.Workbook excelWorkBook = excelFile.Workbooks.Open("C:\Sales Monitoring Report\Transaction.xls") excelFile.Visible = True excelWorkBook.Activate() End If 

要自动适应第一个工作表中的列,请在工作簿激活后插入以下行:

 excelWorkBook.Worksheets(1).Columns.AutoFit() excelWorkBook.Worksheets(1).Rows.AutoFit() 

要打印活动工作簿,请使用PrintOut方法:

 excelWorkBook.PrintOut() 

EZ方式:

  1. 使用列作为目标字段,设置列宽和公式..xls文件。
  2. 使用上面的.xls作为模板,您将在运行时进行复制
  3. 使用.xls的副本存储您的ACCESS DB中的logging

像这样的东西:

'在button事件..

 Private Sub btnXLS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXLS.Click 'copy .xls template to .xls target --> full path 'consider TemplateA.xls as ".xls template" and sFN as ".xls target" (full path) Try My.Computer.FileSystem.CopyFile("TemplateA.xls", sFN, _ FileIO.UIOption.AllDialogs, FileIO.UICancelOption.DoNothing) Dim cnXLS As Data.OleDb.OleDbConnection Dim cnAccess As Data.OleDb.OleDbConnection Dim cmdXLS As New Data.OleDb.OleDbDataAdapter Dim cmdAccess As New Data.OleDb.OleDbDataAdapter Dim dsXls As New DataSet Dim dsAccess As New DataSet 'opening cnAccess connection codes here .. dsAccess as source dataset .. and source table cmdAccess = New Data.OleDb.OleDbDataAdapter("SELECT * FROM .... , cnAccess) cmdXLS.Fill(dsXls, "xls") cnXLS = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" & _ "data source=" & sFN & ";Extended Properties=Excel 8.0;") cnXLS.Open() 'Daftar --> as table name or sheet name in excel cmdXLS = New System.Data.OleDb.OleDbDataAdapter("select * from [Daftar$]", cnXLS) cmdXLS.Fill(dsXls, "xls") For n = 0 To dsAccess.table(source_table).Rows.Count - 1 'some codes here cmdXLS.InsertCommand = New OleDb.OleDbCommand( .. ,cnXls) cmdXLS.InsertCommand.ExecuteNonQuery() Next cnXLS.Close() MsgBox("Transfer finished ! -- " & sFN, MsgBoxStyle.OkOnly, "Info") Exit Sub Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Error) End Try End Sub