日期:2014-05-18  浏览次数:20703 次

菜鸟求高手指教将excel导入sqlserver数据库问题
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.Sql;
using System.Configuration;
using System.IO;
//using System.Collections;
using System.Data.OleDb;
using System.Data.SqlClient;

using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace WindowsFormsApplication1
{
  public partial class Form2 : Form
  {
  public string strFileName;
  public Form2()
  {
  InitializeComponent();
  }

   

  private void button1_Click(object sender, EventArgs e)
  {
  System.Windows.Forms.OpenFileDialog fg = new OpenFileDialog();
  fg.ShowDialog();
  strFileName = fg.FileName;
  }

  private void button2_Click(object sender, EventArgs e)
  {
  string strCell;
  string strCell2;
  string strCell3;
  string strCell4;
  string strCell5;
  string strCell6;
  string strCell7;
  string strCell8;
  string strCell9;
  string strCell10;
  string strCell11;
  string strCell12;
  string strCell13;
  string strCell14;
  string strCell15;
  string strCell16;
  string strCell17;
  string strCell18;
   
  string[] cellsrng1;
  int iFlg = 0;
  int iCol;//列
  int iRow;//行
  string aa;
  int maxRow;//最大行数

  //创建Application对象 
  Excel.Application xApp = new Excel.Application();
  xApp.Visible = false;

  //打开工作表
  Excel.Workbook xBook = xApp.Workbooks.Add(strFileName);

  //工作表最大有效行数列数
  Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1];

  maxRow = xSheet.Application.get_Range("A65536", Type.Missing).get_End(Excel.XlDirection.xlUp).Row;[/color] SqlConnection sc1 = new SqlConnection();
  sc1.ConnectionString = "Data Source=PC-201007291119;Initial Catalog=sb;Integrated Security=True";
  string sql5 = "TRUNCATE TABLE sbtz";
  try
  {
  sc1.Open();
  //SqlCommand cmd0 = new SqlCommand("delete * from 月度成本表", sc);
  //cmd0.ExecuteNonQuery();
  SqlCommand cmd = new SqlCommand(sql5, sc1);
  cmd.ExecuteNonQuery();
  sc1.Close();
  }
  catch (SqlException sqlexp)
  {
  sc1.Close();
  MessageBox.Show(sqlexp.Message);
  MessageBox.Show(sql5);
  }

  for (iRow = 3; iRow <= maxRow; iRow++)
  {
  strCell = "A" + iRow;//序
  strCell2 = "B&qu