Import dữ liệu vào một worksheet của một workbook excel chưa tồn tại từ tệp XML

15 897 0
Import dữ liệu vào một worksheet của một workbook excel chưa tồn tại từ tệp XML

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

1 Lí chọn đề tài: Chúng ta sống kỷ nguyên mà thành tựu khoa học công nghệ xuất cách mau lẹ đổi cách nhanh chóng Nghành công nghệ thông tin ngày chứng tỏ vị trí xuất nhiều lĩnh vực, nơi, chốn đời sống Có thể nói, kinh tế toàn cầu chịu ảnh hưởng sâu sắc từ công nghệ thông tin mà có không vai trò ngành công nghệ phần mềm Các phần mềm làm ứng dụng phục vụ cho công viêc, hoạt động công ty, tổ chức Và nhiều ngôn ngữ đời, ngôn ngữ xml XML (viết tắt từ tiếng Anh eXtensible Markup Language, “Ngôn ngữ Đánh dấu Mở rộng”) ngôn ngữ đánh dấu W3C đề nghị Mục đích XML đơn giản hóa việc chia sẻ liệu hệ thống khác nhau, đặc biệt hệ thống kết nối với Internet Đặc điểm XML cung cấp phương tiện dùng văn (text) để mô tả thông tin áp dụng cấu trúc dạng cho thông tin Tại mức bản, thông tin thể dạng text, chen thẻ đánh dấu (markup) với nhiệm vụ ký hiệu phân chia thông tin thành cấu trúc có thứ bậc liệu ký tự, phần tử dùng để chứa liệu, thuộc tính phần tử Vì nhóm chúng em định chon đề tài “ Import liệu vào WorkSheet Workbook Excel chưa tồn từ tệp XML” Qua nhóm chúng em xin chân thành cảm ơn thầy Ngô Đình Thưởng nhiệt tình giúp đỡ đề tài Mục đích nghiên cứu - Tìm hiểu đề tài “ Import liệu vào WorkSheet Workbook Excel chưa tồn từ tệp XML Tra cứu cách dùng phưong thức CreateObject ("Excel.Application") - Thiết kế Demo Import liệu Phương pháp nghiên cứu - Phương pháp tiếp cận thu thập thông tin: website - Phương pháp nghiên cứu tài liệu: sách, nghiên cứu khoa học - Phương pháp phi thực nghiệm - Phương pháp thực nghiệm Chương1: Tổng quan XML I Giới thiệu chung ngôn ngữ XML Giới thiệu chung • XML ngôn ngữ tổng quát dùng để lưu trữ liệu thẻ có nghĩa • Được định nghĩa tổ chức mạng toàn cầu Word wide web consotium • • Là ngôn ngữ đánh dấu độc lập với phần mềm, phần cứng Cho phép cấu trúc truyền liệu hệ thống không đồng Cấu trúc xml: Có phần  Cấu trúc logic: định nghĩa phần tử, thuộc tính, kiểu liệu, vv  Cấu trúc vật lý: chứa liệu phần tử chứa liệu text, hình ảnh, media, vv Có tên mở rộng xml Ví dụ: Hello Well come to my page Giải thích:  Thẻ khai báo thị xử lí đặt dòng Trong đó: - phần tử gốc liệu - , phần tử định nghĩa bên phần tử gốc, chứa liệu phần tử gốc II Lợi ích Khi Sử Dụng XML - Dễ dàng xử lí trao đổi liệu - Mô tả liệu cách liệu muốn thể thông qua thẻ - Tổ chức liệu có cấu trúc phân cấp - XML tách rời liệu,sử dụng XML liệu lưu trữ - tập tin XML riêng biệt XML mô tả thông tin đối tượng phức tạp mà CSDL quan hệ - giải XML dùng để chia sẻ liệu với tập tin văn dễ hiểu XML dùng để chuyển đổi liệu hệ thống không tương thích XML dùng để lưu trữ liệu làm cho liệu hữu ích Chương 2: NỘI DUNG NGHIÊN CỨU Demo chương trình Xây dựng form có khuôn dạng hình vẽ Gồm có đối tượng: btnBrowser: button lbFilePath: label btnImport: button dtgResult: datagirdview btnExport: button Cơ sở liệu: gồm tệp sample export.xls Mã nguồn Imports System.Data.OleDb Public Class Form1 Dim connectionstring As String Dim dtStudentGrade As DataTable Dim dtExcelData As DataTable Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim dt As New DataTable Dim x As String dt.Columns.Add("col1") Dim drow As DataRow = dt.NewRow drow(0) = "test" dt.Rows.Add(drow) x = dt.Rows(0)(0) 'x = dt.Rows(0)(1) Dim field() As String field(0) = "" field(1) = "" field(2) = "" field(3) = "" field(4) = "" field(5) = "" field(6) = "" field(7) = "" field(8) = "" field(9) = "" field(10) = "" field(11) = "" field(12) = "" field(13) = "" End Sub Private Sub btnBrowser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowser.Click OpenFileDialog1.FileName = "" OpenFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel(2007) files (*.xlsx)|*.xlsx| All files (*.*)|*.*" OpenFileDialog1.ShowDialog() lbFilePath.Text = OpenFileDialog1.FileName End Sub Function ReadExcelFile() 'Use OleDbDataAdapter to provide communication between the DataTable and the OleDb Data Sources Dim da As New OleDbDataAdapter 'Use DataTable as storage of data from excel Dim dt As New DataTable 'Use OleDbCommand to execute our SQL statement Dim cmd As New OleDbCommand 'Use OleDbConnection that will be used by OleDbCommand to connect to excel file Dim xlsConn As OleDbConnection Dim sPath As String = String.Empty sPath = Me.lbFilePath.Text 'Create a new instance of connection and set the datasource value to excel's path xlsConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath & ";Extended Properties=Excel 12.0") 'Use try catch block to handle some or all possible errors that may occur in a 'given block of code, while still running code Try 'Open the connection xlsConn.Open() 'Set the command connection to opened connection cmd.Connection = xlsConn 'Set the command type to CommandType.Text in order to use SQL statment constructed here 'in code editor cmd.CommandType = CommandType.Text 'Assigned the command text to query the excel as shown below cmd.CommandText = ("select * from [Sheet1$]") 'Assign the cmd to dataadapter da.SelectCommand = cmd 'Fill the datatable with data from excel file using DataAdapter da.Fill(dt) Catch 'This block Handle the exception MsgBox(ErrorToString) Finally 'We need to close the connection and set to nothing This code will still execute even the code raised an error xlsConn.Close() xlsConn = Nothing End Try Return dt End Function Public Sub SaveToDB(ByVal iRowIndex As Long) Dim conn As New OleDbConnection Dim sConnString As String Dim cmd As New OleDbCommand Dim sSQL As String = String.Empty Try 'Check if the path has a backslash in the end of string If Microsoft.VisualBasic.Right(Application.StartupPath, 1) = "\" Then sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "dbexport.accdb;Persist Security Info=False;" Else sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\dbexport.accdb;Persist Security Info=False;" End If 'create a new instance of connection conn = New OleDbConnection(sConnString) 'open the connection to be used by command object conn.Open() 'Set the command's connection to our opened connection cmd.Connection = conn 'Set the command type to CommandType.Text in order to use SQL statment constructed here 'in code editor cmd.CommandType = CommandType.Text 'Set the comment text to insert the data to database cmd.CommandText = "INSERT INTO students_grade ( student_no, student_name, grade ) VALUES(@student_no, @student_name, @grade)" 'Add parameters in order to set the values in the query cmd.Parameters.Add("@student_no", OleDbType.VarChar).Value = dtExcelData.Rows(iRowIndex)(0) cmd.Parameters.Add("@student_name", OleDbType.VarChar).Value = dtExcelData.Rows(iRowIndex)(1) 'This is just a sample of how to check if the field is null cmd.Parameters.Add("@grade", OleDbType.Numeric).Value = IIf(Not IsDBNull(dtExcelData.Rows(iRowIndex)(2)), dtExcelData.Rows(iRowIndex)(2), Nothing) cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ErrorToString) Finally conn.Close() End Try End Sub Public Sub Load_Data() Dim conn As New OleDbConnection Dim sConnString As String Dim cmd As New OleDbCommand Dim da As New OleDbDataAdapter Try 'create a new instance of dtStudentGrade, this datatable will be used to export 'data from database to excel dtStudentGrade = New DataTable 'Check if the path has a backslash in the end of string If Microsoft.VisualBasic.Right(Application.StartupPath, 1) = "\" Then sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "dbexport.accdb;Persist Security Info=False;" Else sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\dbexport.accdb;Persist Security Info=False;" End If 'create a new instance of connection conn = New OleDbConnection(sConnString) 'open the connection to be used by command object conn.Open() 'Set the command's connection to our opened connection cmd.Connection = conn 'Set the command type to CommandType.Text in order to use SQL statment constructed here 'in code editor cmd.CommandType = CommandType.Text 'Set the comment text to load the data from database cmd.CommandText = "select * from students_grade" 'assign the cmd object to dataadapter selectcommand property in order to use it to fill the dtStudentGrade da.SelectCommand = cmd 'Populate the dtStudentGrade with the data from database da.Fill(dtStudentGrade) 'Set the datagridview datasource to dtStudentGrade in order to dispaly the data to user dtgResult.DataSource = dtStudentGrade Catch ex As Exception MsgBox(ErrorToString) Finally conn.Close() End Try End Sub Public Sub ImportToDB() 'Create a new instance of dtExcelData datatable dtExcelData = New DataTable 'Set the cursor to wait cursor Windows.Forms.Cursor.Current = Cursors.WaitCursor 'Call ReadExcelFile function to get the data from excel dtExcelData = ReadExcelFile() 'Reset the progressbar Me.ProgressBar1.Value = 'Get the DataTable row count to set the progressbar maximum value Me.ProgressBar1.Maximum = dtExcelData.Rows.Count Me.ProgressBar1.Visible = True 'Use looping to read the value of field in each row in DataTable For i = To dtExcelData.Rows.Count - 'Check if the student number has a value If Not IsDBNull(dtExcelData.Rows(i)(0)) Then 'call save procedure and pass the row varialble i(row index) as parameter to save each the value of each field SaveToDB(i) 'Increase the value of progressbar to inform the user Me.ProgressBar1.Value = Me.ProgressBar1.Value + End If Next dtExcelData = Nothing 'Call the Load_Data procedure that will load the data and display it to DataGrid Load_Data() 'Inform the user that the importing of data has been finished MsgBox("Data has successfully imported.", MsgBoxStyle.OkOnly, "Import Export Demo") End Sub Private Sub btnImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click 'Check if there's a selected excel file to be imported If Len(Trim(Me.lbFilePath.Text)) > Then ImportToDB() Else 'Inform the user if no selected excel file MsgBox("Please select a file.", MsgBoxStyle.OkOnly, "Import Export Demo") End If End Sub Private Sub releaseObject(ByVal obj As Object) Try 'Call the release object function to release the object before disposing System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally 'Call the Garbage collector to free the resources consumed by created instances GC.Collect() End Try End Sub Private Sub ExportExcel() 'Create excel objects Dim xlApp As Microsoft.Office.Interop.Excel.Application Dim xlBook As Microsoft.Office.Interop.Excel.Workbook Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet Dim oValue As Object = System.Reflection.Missing.Value Dim sPath As String = String.Empty 'cereate new object SaveFileDialog that will be use to save the file Dim dlgSave As New SaveFileDialog 'Create a new instance of databale, this will server as container of data Dim dt As New DataTable 'We need to set the default extension to xls so the SaveFileDialog will save the file 'as excel file dlgSave.DefaultExt = "xls" 'Set the filter for SaveFileDialog dlgSave.Filter = "Microsoft Excel|*.xls" 'set the initial path, you may set a different path if you like dlgSave.InitialDirectory = Application.StartupPath 'Export the data if the user click the ok button of SaveFileDialog If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then Try 'Create a new instance of excel application xlApp = New Microsoft.Office.Interop.Excel.Application 'Create an excel workbook xlBook = xlApp.Workbooks.Add(oValue) 'Create an excel sheet named sheet1 xlSheet = xlBook.Worksheets("sheet1") Dim xlRow As Long = Dim xlCol As Short = 'To create a column for excel we need to loop through DataTable(dtStudentGrade) For Each col As DataColumn In dtStudentGrade.Columns 'Get the column name and assigned it to excel sheet cells 'to assign value to each cell we need to specify the row and column xlSheet.Cells(row, column) xlSheet.Cells(1, xlCol) = col.ColumnName 'Increment the xlCol so we can set another column xlCol += Next 'reset the progressbar Me.ProgressBar1.Visible = True Me.ProgressBar1.Minimum = Me.ProgressBar1.Maximum = dtStudentGrade.Rows.Count 'Loop through dtStudentGrade to get the value of each field in a row For Each row As DataRow In dtStudentGrade.Rows 'Reset xlCol's value to xlCol = 'Loop through dtStudentGrade and set the value of each excel sheet cells For Each col As DataColumn In dtStudentGrade.Columns 'Assign the value of each field to selected excel sheet cell xlSheet.Cells(xlRow, xlCol) = row(xlCol - 1) 'Increment the xlCol so we can set another the the value of another cell xlCol += Next 'Increment the xlCol xlRow += 'Set the value of progressbar If Me.ProgressBar1.Maximum > Me.ProgressBar1.Value + Then Me.ProgressBar1.Value = Me.ProgressBar1.Value + End If Next 'Set the filename and set the filename to xlx to save the file as excel 2003 'You may remove the Replace function and save the file with xlsx(excel 2007) extension Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx") 'save the file xlSheet.SaveAs(sFileName) 'close the workbook xlBook.Close() 'Quit the application using this code xlApp.Quit() 'Release the objects used by excell application by calling our procedure releaseObject releaseObject(xlApp) releaseObject(xlBook) releaseObject(xlSheet) 'Reset the progressbar Me.ProgressBar1.Value = Me.ProgressBar1.Visible = False 'inform the user if successfull MsgBox("Data successfully exported.", MsgBoxStyle.Information, "PRMS/SOB Date Tagging") Catch MsgBox(ErrorToString) Finally End Try End If End Sub Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click ExportExcel() End Sub End Class KẾT LUẬN Kết đạt : - Thông qua đề tài “ Import liệu vào WorkSheet Workbook Excel chưa tồn từ tệp xml” tất thành viên nhóm hiểu rõ cách nghiên cứu báo khoa học từ rút kinh nghiệm thân để làm đề tài, khóa luận, tập lớn để phục vụ cho việc học tập làm việc sau - Hơn nữa, đề tài giúp chúng em hiểu rõ ngôn ngữ Xml ứng dụng xml, biết cách import liệu vào WorkSheet Workbook Excel chưa tồn từ tệp xml Một số hạn chế - Chương trình code dài, khó hiểu - Sử dụng System.Data.OleDB khó hiểu so với sử dụng Reference Imports Microsoft.Office.Interop.Excel Project Hướng phát triển đề tài - TÀI LIỆU THAM KHẢO [1] Tài liệu xml [2] Tham khảo trang website [3] Giáo trình phương pháp nghiên cứu khoa học Nguyễn Tấn Lê [...]... hiểu rõ hơn về ngôn ngữ Xml và ứng dụng của xml, biết cách import dữ liệu vào một WorkSheet của một Workbook Excel chưa tồn tại từ tệp xml 2 Một số hạn chế - Chương trình code dài, khó hiểu - Sử dụng System.Data.OleDB khó hiểu hơn so với sử dụng Reference và Imports Microsoft.Office.Interop .Excel trong Project 3 Hướng phát triển của đề tài - TÀI LIỆU THAM KHẢO [1] Tài liệu về xml [2] Tham khảo trên... sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click ExportExcel() End Sub End Class KẾT LUẬN 1 Kết quả đạt được : - Thông qua đề tài “ Import dữ liệu vào một WorkSheet của một Workbook Excel chưa tồn tại từ tệp xml tất cả các thành viên trong nhóm đã hiểu rõ được cách nghiên cứu một bài báo khoa học từ đó rút kinh nghiệm bản thân để làm các đề tài, khóa luận, bài tập lớn để phục... Microsoft.Office.Interop .Excel. Application 'Create an excel workbook xlBook = xlApp.Workbooks.Add(oValue) 'Create an excel sheet named sheet1 xlSheet = xlBook.Worksheets("sheet1") Dim xlRow As Long = 2 Dim xlCol As Short = 1 'To create a column for excel we need to loop through DataTable(dtStudentGrade) For Each col As DataColumn In dtStudentGrade.Columns 'Get the column name and assigned it to excel sheet cells... collector to free the resources consumed by created instances GC.Collect() End Try End Sub Private Sub ExportExcel() 'Create excel objects Dim xlApp As Microsoft.Office.Interop .Excel. Application Dim xlBook As Microsoft.Office.Interop .Excel .Workbook Dim xlSheet As Microsoft.Office.Interop .Excel .Worksheet Dim oValue As Object = System.Reflection.Missing.Value Dim sPath As String = String.Empty 'cereate...'Check if there's a selected excel file to be imported If Len(Trim(Me.lbFilePath.Text)) > 0 Then ImportToDB() Else 'Inform the user if no selected excel file MsgBox("Please select a file.", MsgBoxStyle.OkOnly, "Import Export Demo") End If End Sub Private Sub releaseObject(ByVal obj As Object) Try 'Call the release object... the filename to xlx to save the file as excel 2003 'You may remove the Replace function and save the file with xlsx (excel 2007) extension Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx") 'save the file xlSheet.SaveAs(sFileName) 'close the workbook xlBook.Close() 'Quit the application using this code xlApp.Quit() 'Release the objects used by excell application by calling our procedure... file 'as excel file dlgSave.DefaultExt = "xls" 'Set the filter for SaveFileDialog dlgSave.Filter = "Microsoft Excel| *.xls" 'set the initial path, you may set a different path if you like dlgSave.InitialDirectory = Application.StartupPath 'Export the data if the user click the ok button of SaveFileDialog If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then Try 'Create a new instance of excel application... a row For Each row As DataRow In dtStudentGrade.Rows 'Reset xlCol's value to 1 xlCol = 1 'Loop through dtStudentGrade and set the value of each excel sheet cells For Each col As DataColumn In dtStudentGrade.Columns 'Assign the value of each field to selected excel sheet cell xlSheet.Cells(xlRow, xlCol) = row(xlCol - 1) 'Increment the xlCol so we can set another the the value of another cell xlCol +=

Ngày đăng: 04/08/2016, 07:24

Từ khóa liên quan

Mục lục

  • I. Giới thiệu chung về ngôn ngữ XML

  • II. Lợi ích Khi Sử Dụng XML

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan