c#读取excel中的数据到sql server,包括c#读取excel的数据

来源:互联网 发布:淘宝退出游戏专营卖家 编辑:程序博客网 时间:2024/06/02 19:26

代码仅供参考,不能直接复制,理解代码更重要,复制粘贴没有任何意义

1.采用excel的com组件接口. 添加引用,在vs2015中添加引用,com组件中找到excel的接口.

这样添加不会与系统中excel版本冲突,如果下载Microsoft.Office.Interop.Excel.dll文件的话可能因为版本不同而无法使用.

在新建excel application时会报错,需要将引用的Microsoft.Office.Interop.Excel属性"嵌入互操作类型"改为false即可.

准备工作完成

首先连接数据库,

然后新建excel的程序,

取得工作簿名,也就是excel文件名,

之后取得表名,也就是sheet名

然后选择一个范围 range,先写行,在写列,

如果是取得某一个单元格的范围,俩个值相同即可,

将excel的范围内的值全部存在arry1中,

然后将arry1中的数据存为string类型arry中

arr中的值即为excel中单元格的值.



using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;using Microsoft.Office.Interop.Excel;using System.IO;using System.Reflection;using Excel = Microsoft.Office.Interop.Excel;using System.Diagnostics;namespace ExcelTest{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        public void OpenExcel(string strFileName)        {            string ConStr = "server=.;database=AFKdb;uid=sa;pwd=123";            SqlConnection conn = new SqlConnection(ConStr);            conn.Open();            SqlCommand cmd = new SqlCommand();            cmd.Connection = conn;//以上为连接数据库            object missing = System.Reflection.Missing.Value;            Excel.Application excel = new Excel.ApplicationClass();//lauch excel application            if (excel == null)            {                Console.WriteLine("Can't access excel");            }            else            {                excel.Visible = false; excel.UserControl = true;// 以只读的形式打开EXCEL文件                Excel.Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,                 missing, missing, missing, true, missing, missing, missing, missing, missing);//取得第一个工作薄                for (int nv = 13; nv < 17; nv++)               {              // int nv = 13;//sheet                    Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(nv);//get_Intem(n)取得第n个sheet                //以下俩行代码取得总记录行数(包括标题行)                int rowsint = ws.UsedRange.Cells.Rows.Count;//得到行数                int columnsint = ws.UsedRange.Cells.Columns.Count;//得到列数                                for (int month = 0; month < columnsint; month++)//循环列                {                                        Excel.Range rng1 = ws.Cells.get_Range(ws.Cells[2, month + 1], ws.Cells[rowsint, month + 1]);//获取数据的范围,先写行在写列,此处为获取一列的数据                    Excel.Range rng2 = ws.Cells.get_Range(ws.Cells[1, month + 1], ws.Cells[1, month + 1]);//返回某单元格的值,先写行在写列                    object[,] arry1 = (object[,])rng1.Value2;   //get range's value    将数据储存的arry1中                    string[,] arry = new string[rowsint, 1];                    for (int q = 1; q <= rowsint - 1; q++)//转化为arry                        {                        arry[q - 1, 0] = arry1[q, 1].ToString();                    }                    for (int j = 0; j < rowsint - 1; j++)//数据已存储进arry,即可对数据进行操作了!                            //以下代码对excel的数据的操作,没有多大的借鉴作用                    {                        //cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime)values(NEWID(), '1', '101', '"+rng2.Value2+"', '"+ arry[j, 0]+"', getdate())";//身高男                        //cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime)values(NEWID(), '1', '102', '" + rng2.Value2 + "', '" + arry[j, 0] + "', getdate())";//体重男                        // cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime)values(NEWID(), '1', '10"+ textBox1.Text.Trim()+"', '" + rng2.Value2 + "', '" + arry[j, 0] + "', getdate())";//第几个sheet男                        //cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime)values(NEWID(), '2', '10" + nv.ToString() + "', '" + rng2.Value2 + "', '" + arry[j, 0] + "', getdate())";//第几个sheet女                        //cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime,unit)values(NEWID(), '1', '100" + (month+1).ToString() + "', '-1 ', '" + arry[j, 0] + "', getdate(),'周')";//第一次男                        // cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime,unit)values(NEWID(), '2', '100" + (month + 1).ToString() + "', '-1 ', '" + arry[j, 0] + "', getdate(),'周')";                       // cmd.CommandText += "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime,unit)values(NEWID(), '2', '200" +(nv-10).ToString()+ "', '" + rng2.Value2 + "', '" + arry[j, 0] + "', getdate(),'小时')";//各项时间                        cmd.CommandType = CommandType.Text;                        int i = Convert.ToInt32(cmd.ExecuteNonQuery());                        label2.Text = "第"+nv.ToString()+"个sheet,"+"第"+month.ToString()+"列"+j.ToString();                        cmd.CommandText = "";                    }                                                        }                                if (conn.State == ConnectionState.Open)                {                    label1.Text = "数据库第(" + nv + ")sheet已经导入";                }                            }        }            excel.Quit(); excel = null;            Process[] procs = Process.GetProcessesByName("excel");            foreach (Process pro in procs)            {                pro.Kill();//没有更好的方法,只有杀掉进程            }            GC.Collect();        }        private void button1_Click(object sender, EventArgs e)        {            if(textBox1.Text=="")            {                MessageBox.Show("请输入要连接的数据库");            }            else            {                try                {                                        OpenExcel(@"D:\work\testc#\chapter1\sqlConnection\bin\Debug\test2.xlsx");                  //  cmd.CommandText = "insert AFKdb.dbo.AllData(GUID, sex, int_item, int_month, num_value, createtime)values(NEWID(), '1', '100', '0', '50.4034', getdate())";                                   }                catch                {                    MessageBox.Show("连接数据库失败");                }            }        }    }}

我建立的是窗口应用程序

关于数据库的操作,要提示的地方:

暂时忘了,完了再写


1 0