【Ruby】ruby之文件流

使用ruby脚本对excel数据进行读写

一、基本的文件读写操作

  1. readLine读取操作
def readfile
		# chomp去除回车   
		puts "请输入您要导入的文件?"
		# 输入文件的路径
		path = gets.chomp
		# 全局hash数据模块
		datas = []
	begin 
		file = IO.readlines("#{
      
      path}")
		puts file
		titname = []
		file.each_with_index do |line,i| 
			a = line.split(",")
			if i == 0
				titname = a
			end
			linedata = {
    
    }
			titname.each_with_index do |tn,i|
				linedata[tn] = a[i]
			end
			datas[i] = linedata
		end
		puts datas
		
		# 条件查询
		puts "请输入您要查询的内容?"
			find = gets.chomp
			termname = find.split("#")[0]
			termdata = find.split("#")[1]
			
			data = datas[termdata.to_i]
			puts "termname:"+data["#{
      
      termname}"].to_s
			
		# 输入修改的内容
		puts "请输入您要修改的内容?"
			phone = gets.chomp
			
		# 保存文件
		puts "是否保存新文件?"
		    yesorno = gets.chomp
						
			if yesorno == "是"
			   data["#{
      
      termname}"] = phone
			   # 读写模式
			   aFile = File.new("/Users/touyoshitaka/Desktop/test.csv", "r+")
			   if aFile
				  datas.each_with_index do |data,i|
				  # 新数据拼接接收函数
				  myfile = ""
				  titname.each_with_index do |tn,j|
					 myfile << data[tn].chomp+","
				  end
					# 数据拼接
					file[i] =myfile
					
					# 添加一行
					aFile.syswrite(file[i])
					# 换行
					aFile.syswrite("\r\n")
			      end
				  puts "文件保存成功"
			   else
			      puts "文件保存失败"
			   end
			else
				 puts "操作完成"
			end

	# 错误
	rescue => e
		puts e
	end
	
end

readfile
  1. 面向对象的方式封装
# 封装文件的操作
class ReadFile
	def initialize(filepath)
		@filepath = filepath
		@datas = []
		@titname = []
		@termname = ""
		@termdata = ""
		@data = []
	end
	
	def	readfile()
		if @filepath.size == 0
		   @filepath = '/Users/touyoshitaka/Desktop/test.csv'
		end
		
		file = IO.readlines("#{
      
      @filepath}")

		file.each_with_index do |line,i| 
			a = line.split(",")
			if i == 0
				@titname = a
			end
			linedata = {
    
    }
			@titname.each_with_index do |tn,i|
				linedata[tn] = a[i]
			end
			@datas[i] = linedata
		end
		puts @datas
	end
	
	
	def search(find)
		@termname = find.split("#")[0]
		@termdata = find.split("#")[1]
		
		@data = @datas[@termdata.to_i]
		# puts data
		puts "#{
      
      @termname}:"+@data["#{
      
      @termname}"].to_s
		
	end
	
	def update(phone)
		file = []
		@data["#{
      
      @termname}"] = phone
		# 读写模式
		aFile = File.new(@filepath, "r+")
		if aFile
			 @datas.each_with_index do |da,i|
			 # 新数据拼接接收函数
			 myfile = ""
			 # file[i] = data[:序号].chomp<<","<<data[:手机号码].chomp<<","<<data[:区号].chomp
			 @titname.each_with_index do |tn,j|
				 myfile << da[tn].chomp+","
			 end
				# 数据拼接
				file[i] =myfile
				
				# 添加一行
				aFile.syswrite(file[i])
				# 换行
				aFile.syswrite("\r\n")
		   end
				puts "文件保存成功"
		else
		   puts "文件保存失败"
		end
	end
	
end

# 封装操作的方法
class Perform
	def initialize()
		@rf
		@phone
	end
	
	def read
		puts "请输入您要导入的文件?"
		filepath = gets.chomp
		# new ReadFile
		@rf = ReadFile.new(filepath)
		@rf.readfile()
	end
	
	def seach
		# 条件查询
		puts "请输入您要查询的内容?"
		find = gets.chomp
		@rf.search(find)
	end
	
	def update
		# 输入修改的内容
		puts "请输入您要修改的内容?"
			@phone = gets.chomp
	end
	
	def save
		# 保存文件
		puts "是否保存新文件?"
		yesorno = gets.chomp		
		if yesorno == "是"
		    @rf.update(@phone)
		else
			puts "操作完成"
		end
	end
end

pf = Perform.new()
pf.read
pf.seach
pf.update
pf.save
  1. Excel数据存储到mysql中
=begin
    数据库
	drop table tools;
	create table tools(
	id  bigint(20) not null,
	phone int(12),
	areacode int(4),
	primary key (id)
	)
=end		
require "mysql2"
		
def readWriteMysql
	client = Mysql2::Client.new(
		host: "127.0.0.1",
		username: "root",
		password: "123456",
		database: "rubytools"
	)
# 首先删除原先的数据,创建新数据表
client.query("drop table tools")
client.query("create table tools(id  int(20),
									phone int(12),
									areacode int(4))")

		puts "请输入您要导入的文件?"
		path = gets.chomp
		# path是在终端输入的文件地址
		file = IO.readlines("#{
      
      path}")
		# 字段列名
		titname = []
		# 列名
		insertcol = ""
		# 添加的数据
		insertval = ""
		
		file.each_with_index do |line,i| 
			a = line.split(",")
			if i == 0
				titname = a
			else
				titname.each_with_index do |tn,i|
					# 拼接添加数据的字段名和数据
					if i == 0
						insertcol = tn
						insertval = a[i]
					else
						insertcol = insertcol+","+tn
						insertval = insertval+","+a[i]
					end	
				end
				# 插入数据
				client.query("INSERT INTO tools (#{
      
      insertcol}) VALUES (#{
      
      insertval})")
			end
		end
		
		# 条件查询
		puts "请输入您要查询的内容?"
			find = gets.chomp
			# 终端输入的查询条件(termdata查询序号)
			termname = find.split("#")[0]
			termdata = find.split("#")[1]
			# 查询插入的数据
			seachData = client.query("SELECT #{
      
      termname} FROM tools WHERE id=#{
      
      termdata}")
			seachData.each do |data|
				puts termname+":"+data["phone"].to_s
			end

		# 输入修改的内容
		puts "请输入您要修改的内容?"
			phone = gets.chomp
			
		# 保存文件
		puts "是否保存新文件?"
		    yesorno = gets.chomp
			if yesorno == "是"
			   client.query("UPDATE tools SET #{
      
      termname} = #{
      
      phone} WHERE id = #{
      
      termdata}")
				puts "文件保存成功"
			else
				puts "操作完成"
			end
end

readWriteMysql

二、总结

  1. 安装mysql2
 gem install mysql2
  1. 连接数据库
client = Mysql2::Client.new(
	host: "127.0.0.1",
	username: "root",
	password: "123456",
	database: "rubytools"
)
  1. 对数据库读写进行操作
# 删除表
client.query("drop table tools")

# 新建表
client.query("create table tools(id  int(20),
									phone int(12),
									areacode int(4))")
									
# 添加数据
client.query("INSERT INTO tools (列名1,列名2...) VALUES (数据1,数据2....)")

# 查询
result = client.query("SELECT #{
      
      termname} FROM tools WHERE id=#{
      
      termdata}")
# 返回的result
result.each do |data|
	puts data
end

# 更新字段
client.query("UPDATE tools SET 字段名 = 数据 WHERE id = 1")

猜你喜欢

转载自blog.csdn.net/m0_46537958/article/details/107358232