如何用rails 导入Excel文件数据到数据库

Python019

如何用rails 导入Excel文件数据到数据库,第1张

首先,只是想把一些数据生成excel文件的话,最简单的办法,应该考虑生成CSV,

因为,Ruby支持比较好,而且,你用excel可以直接打开。当然,前提是你的excel没有特别复杂的表结构,样式渲染等

样例如下:

Ruby代码

outfile = File.open('csvout', 'wb')

CSV::Writer.generate(outfile) do |csv|

csv <<['c1', nil, '', '"', "\r\n", 'c2']

...

end

outfile.close

其次,一般用的话可以考虑spreadsheet。就像一楼的老大提供的连接所说,那个例子很好,只是适合你的读取复杂的适合参考。如果,你用不到那么复杂,建议你看下面的说明。

生成excel文件

如果,你想生成一个excel文件,那么首先,就像写文件一个先加载spreadsheet类库,然后,指定编码接着,就可以创建一个Workbook了

Ruby代码

book = Spreadsheet::Workbook.new

在workbook基础上创建Worksheet表单

Ruby代码

sheet1 = book.create_worksheet

当然,你也可以用如下方式创建表单:

Ruby代码

sheet2 = book.create_worksheet :name =>'My Second Worksheet'

sheet1.name = 'My First Worksheet'

那么,这时我们可以采用如下方式加载数据到表单Worksheet#[]=,

Worksheet#update_row, 或者直接给一个指定单元格复制

Ruby代码

sheet1.row(0).concat %w{Name Country Acknowlegement}

sheet1[1,0] = 'Japan'

row = sheet1.row(1)

row.push 'Creator of Ruby'

row.unshift 'Yukihiro Matsumoto'

sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',

'Author of original code for Spreadsheet::Excel' ]

sheet1.row(3).push 'Charles Lowe', 'Author of the ruby-ole Library'

sheet1.row(3).insert 1, 'Unknown'

sheet1.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'

对于格式的处理,可以如下:

Ruby代码

sheet1.row(0).height = 18

format = Spreadsheet::Format.new :color =>:blue,

:weight =>:bold,

:size =>18

sheet1.row(0).default_format = format

bold = Spreadsheet::Format.new :weight =>:bold

4.times do |x| sheet1.row(x + 1).set_format(0, bold) end

最后,保存excel文件

Ruby代码

book.write '/path/to/output/excel-file.xls'

最后,如果是在windows平台下的话,也可以考虑WIN23OLE,处理windows下的转换很强大

Ruby代码

require 'win23ole'

application = WIN32OLE.new('Excel.Application')

worksheet

=application.Workbooks.Open(excelFileName).Worksheets(workSheetName)

worksheet.Activate

contLoop = true # Dummy counter for the loop

while contLoop do

colVal = worksheet.Cells(row, column).Value

if (colVal) then

# 如果这个字段非空,则表示这行有值

# 在这里处理读取

do processing ....

else

# 这里表明结束。

# End the loop

contLoop = false

end

# go to the next Row

row += 1

end

# we are done

application.Workbooks.Close

将文件保存到数据库中,实际上是将文件转换成二进制流后,将二进制流保存到数据库相应的字段中。在SQL Server中该字段的数据类型是Image,在Access中该字段的数据类型是OLE对象。//保存文件到SQL Server数据库中FileInfo fi=new FileInfo(fileName)FileStream fs=fi.OpenRead()byte[] bytes=new byte[fs.Length]fs.Read(bytes,0,Convert.ToInt32(fs.Length))SqlCommand cm=new SqlCommand()cm.Connection=cncm.CommandType=CommandType.Textif(cn.State==0) cn.Open()cm.CommandText="insert into "+tableName+"("+fieldName+") values(@file)"SqlParameter spFile=new SqlParameter("@file",SqlDbType.Image)spFile.Value=bytescm.Parameters.Add(spFile)cm.ExecuteNonQuery()//保存文件到Access数据库中FileInfo fi=new FileInfo(fileName)FileStream fs=fi.OpenRead()byte[] bytes=new byte[fs.Length]fs.Read(bytes,0,Convert.ToInt32(fs.Length))OleDbCommand cm=new OleDbCommand()

发给你一个上传图片并把它存入数据库的例子。

1.前台<table cellpadding="0" cellspacing="0"

<tr<td colspan="2"</td</tr<tr<td<asp:Label ID="Label1" runat="server" Font-Size="9pt" Text="选择文件"</asp:Label</td

<td align="left"<asp:FileUpload ID="FileUpload1" runat="server" Font-Size="9pt" /</td</tr<tr<td</td

<td align="left"

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="保存"/</td</tr<tr<td</td

<td align="left"

<asp:Label ID="Label3" runat="server" Font-Size="9pt" Width="216px"</asp:Label</td</tr</table

2.后台using System.IO

using System.Data.SqlClient

public partial class _Default : System.Web.UI.Page{protected void Button1_Click(object sender, EventArgs e){try{if (this.FileUpload1.PostedFile.FileName != ""){string ImgPath = FileUpload1.PostedFile.FileName

string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("\\") + 1)

string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf(".") + 1)

int FileLen = this.FileUpload1.PostedFile.ContentLength

Byte[] FileData = new Byte[FileLen]

HttpPostedFile hp = FileUpload1.PostedFile

Stream sr = hp.InputStream

sr.Read(FileData, 0, FileLen)

SqlConnection con = new SqlConnection("server=(local)user id=sapwd=database=db_07")

con.Open()

SqlCommand com = new SqlCommand("INSERT INTO tb_08 (name) VALUES (@imgdata)", con)

com.Parameters.Add("@imgdata", SqlDbType.Image)

com.Parameters["@imgdata"].Value = FileData

Label3.Text = "保存成功!"}else{Label3.Text = "请选择文件!"}}catch (Exception error){Label3.Text = "处理失败!原因为:" + error.ToString()}}}