Created
October 8, 2019 02:28
-
-
Save imvenj/92abb9d65db3c2c9763e545e39412114 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'rubyXL' | |
workbook = RubyXL::Parser.parse("test.xlsx") | |
workbook.worksheets.each do |worksheet| | |
out_sql = open("#{worksheet.sheet_name}.sql", 'w+') | |
current_row = 1 # 跳过第一行表头 | |
blank_rows = 0 # 空行计数器 | |
table_name = '' | |
primary_keys = [] | |
while (true) do | |
row = worksheet[current_row] | |
if row.nil? | |
blank_rows += 1 | |
else | |
first_column_of_row = row[1] | |
if first_column_of_row.nil? or first_column_of_row.value.nil? | |
blank_rows += 1 | |
else | |
blank_rows = 0 # 发现非空行,重置计数器 | |
cell_value = first_column_of_row.value | |
begin | |
matches = cell_value.strip.match(/^(.+?)[\((](.+?)[\))]$/) | |
rescue Exception => e | |
puts "current_row #{current_row}" | |
puts e | |
end | |
if matches.nil? # Normal data | |
if row[3].nil? or row[3].value.nil? # 备注行 | |
current_row += 1 | |
next | |
end | |
col_name = row[1].value | |
col_type = row[3].value.upcase | |
col_length = row[4].nil? ? '0' : row[4].value.to_s | |
if row[4].nil? or row[4].value.to_s.strip == '' | |
out_sql.puts "\t#{col_name} #{col_type}," | |
else | |
out_sql.puts "\t#{col_name} #{col_type}(#{row[4].value})," | |
end | |
unless row[5].nil? | |
primary_keys << col_name if row[5].value && row[5].value.strip == 'pk' | |
end | |
else # Found new table!!! | |
# 为上一张表增加约束 | |
if table_name != '' | |
out_sql.puts "\tCONSTRAINT PK_#{table_name} PRIMARY KEY (#{primary_keys.join(', ')})" if primary_keys.size > 0 | |
out_sql.puts ");" | |
out_sql.puts | |
end | |
# 开始下一张表 | |
table_name = matches[1] | |
primary_keys = [] # 重置主键名数组 | |
out_sql.puts "--#{matches[2]}" | |
out_sql.puts "CREATE TABLE #{matches[1]} (" | |
end | |
end | |
end | |
current_row += 1 | |
if blank_rows > 10 | |
# 为上一张表增加约束 | |
out_sql.puts "\tCONSTRAINT PK_#{table_name} PRIMARY KEY (#{primary_keys.join(', ')})" if primary_keys.size > 0 | |
out_sql.puts ");" | |
break | |
else | |
next | |
end | |
end | |
out_sql.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment