Created
January 18, 2013 09:25
-
-
Save ricdeez/4563403 to your computer and use it in GitHub Desktop.
Ruby Import data to Access from Excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%w(pp win32ole).each { |dep| require dep } | |
db = 'C:\Users\rdapaz\Documents\Statement of Compliance.accdb' | |
cs = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=#{db};" | |
rs = WIN32OLE.new('ADODB.Recordset') | |
conn = WIN32OLE.new('ADODB.Connection') | |
conn.Open(cs) | |
rs.Open("[SoC]", conn, 1, 3) | |
conn.Execute("DELETE * FROM SoC") | |
sheets = { | |
"1300-PR-PHL-1007" => {id: 9, col1: 'J', col2: 'K', start: 6}, | |
"1300-IN-SPC-1003" => {id: 10, col1: 'D', col2: 'E', start: 2}, | |
"1300-IN-SPC-1016" => {id: 11, col1: 'D', col2: 'F', start: 6}, | |
"1300-IN-SPC-1017" => {id: 12, col1: 'J', col2: 'K', start: 2}, | |
"1300-IN-SPC-1018" => {id: 13, col1: 'J', col2: 'K', start: 2}, | |
"1300-IN-SOW-1002" => {id: 14, col1: 'J', col2: 'K', start: 2}, | |
"1300-IN-SOW-1006" => {id: 15, col1: 'J', col2: 'K', start: 2} | |
} | |
class ExcelConst | |
end | |
xl = WIN32OLE.new('Excel.Application') | |
xl.Visible = true | |
xl.DisplayAlerts = false | |
WIN32OLE.const_load(xl,ExcelConst) | |
path_to_doc = 'C:\data\share\OutstandingDocs\SoC\Statement of Conformance_SP_HVB_PN.xlsm' | |
wb = xl.Workbooks.Open(path_to_doc) | |
sheets.each do |sht_name, hash| | |
sht = wb.Worksheets(sht_name) | |
eof = sht.Range("C65536").End(ExcelConst::XlUp).row | |
(hash[:start] .. eof).each do |row| | |
section_no = (sht.Range("B#{row}").value).nil? ? "" : sht.Range("B#{row}").value | |
section_heading = (sht.Range("C#{row}").value).nil? ? "" : sht.Range("C#{row}").value | |
comply_text = (sht.Range("#{hash[:col1]}#{row}").value).nil? ? "" : sht.Range("#{hash[:col1]}#{row}").value | |
comply_desc = (sht.Range("#{hash[:col2]}#{row}").value).nil? ? "" : sht.Range("#{hash[:col2]}#{row}").value | |
begin | |
rs.AddNew | |
rs.Fields("DocFKID").value = hash[:id] | |
rs.Fields("SectionNo").value = section_no | |
rs.Fields("SectionHeading").value = section_heading | |
rs.Fields("ComplyText").value = comply_text.gsub(/\n/, "\r\a") | |
rs.Fields("ComplyDesc").value = comply_desc.gsub(/\n/, "\r\a") | |
rs.Update | |
rescue | |
puts "Unable to process field #{sht_name}: #{section_no}" | |
next | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment