我在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
答案 0 :(得分:1)
要在第一个工作表中自动调整列,请在工作簿激活后插入以下行:
excelWorkBook.Worksheets(1).Columns.AutoFit()
excelWorkBook.Worksheets(1).Rows.AutoFit()
要打印活动工作簿,请使用PrintOut方法:
excelWorkBook.PrintOut()
答案 1 :(得分:1)
EZ方式:
这样的事情:
'在按钮事件中..
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