111,126
社区成员
发帖
与我相关
我的任务
分享
DataTable dt = new DataTable();
dt.Columns.Add("year", typeof(DateTime));
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
namespace IOdatabase
{
public partial class Form1 : Form
{
public Sheets sheets;
public Worksheet datasheet;
public Range range; //数据表中对应范围的数据
public System.Array Cellarray; //数据表中对应范围的数据转换为数组形式
public SqlConnection conn;
public Form1()
{
InitializeComponent();
this.textBox1.ReadOnly = true; //设置TextBox为只读
this.textBox1.BackColor = Color.White; //设置TextBox的背景色为白色
this.dataGridView1.ReadOnly = true; //设置DataGridView为只读
}
private void button1_Click(object sender, EventArgs e) //按钮:“导入表”
{
this.textBox1.Clear();
OpenFileDialog openFile1 = new OpenFileDialog(); //动态添加OpenFileDialog控件,用于弹出一个窗口提示用户打开文件
openFile1.Filter = "Microsoft Excel 工作表|*.xls";
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int count = 0;
string OpenFilePath = openFile1.FileName;
Microsoft.Office.Interop.Excel.ApplicationClass app = new ApplicationClass();
app.Visible = false;
WorkbookClass Workbook = (WorkbookClass)app.Workbooks.Open(OpenFilePath);//打开对应路径的Excel
object missing = Type.Missing;
sheets = Workbook.Worksheets;
this.textBox1.Text += "正在解析..." + Environment.NewLine;
//判断导入的表是否是完整sheet的表
foreach (Worksheet sheet in sheets)
{
if (sheet.Name == "寿险公司" || sheet.Name == "财产公司" || sheet.Name == "明细表" || sheet.Name == "赔款")
{
count++;
}
}
if (count > 0 && count < 4)
{
this.textBox1.Text += "导入的表,其中包含的sheet不完整,请重新导入!";
return;
}
else if (count == 0)
{
this.textBox1.Text += "导入了格式完全错误的表,请重新导入!";
return;
}
else
{
this.textBox1.Text += "表的格式完全正确,正在导入数据库!"+Environment.NewLine;
}
// 解析出表的“年”、“月”
datasheet = null;
foreach (Worksheet sheet in sheets)
{
if (sheet.Name == "寿险公司") //读取“寿险公司”的sheet;
{
datasheet = sheet;
break;
}
}
range = datasheet.get_Range("G2");
string data = (System.String)range.Value;
string[] dataArray = data.Split(new char[2] { '年', '月' }); //dataArray[0]为年份,dataArray[1]为月份
/*
要导入填充函数的三个参量:sheets(完整的表)、
dataArray[0](年份)、dataArray[1](月份)
*/
//---------------导入填充函数---------------//
LoadSheetsFunction(Convert.ToInt32(dataArray[0]), Convert.ToInt32(dataArray[1]));
//-------------------回收Excel进程-------------------//
Workbook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(Workbook);
Workbook = null;
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
sheets = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(datasheet);
datasheet = null;
GC.Collect();
}
}
void LoadSheetsFunction(int year, int month) //填充函数
{
string connString = @"
server = (local);
integrated security = true;
database = ExcelDatabase
"; // 连接数据库的字符串
using (conn = new SqlConnection(connString))
{
conn.Open();
LoadLifeInsuranceCompany(year, month); //填充“寿险公司”
}
}
void LoadLifeInsuranceCompany(int year, int month) //填充“寿险公司”的函数
{
foreach (Worksheet sheet in sheets)
{
if (sheet.Name == "寿险公司") //读取“寿险公司”的sheet;
{
datasheet = sheet;
}
}
SqlCommand Newcmd = new SqlCommand("select * from LifeInsuranceCompany where (year=" + year.ToString() + ")" + "and (month=" + month.ToString() + ")", conn);
SqlDataReader rdr = Newcmd.ExecuteReader();
if (!rdr.HasRows)
{
rdr.Close();
string sql = @"select * from LifeInsuranceCompany";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "LifeInsuranceCompany");
System.Data.DataTable dt = ds.Tables["LifeInsuranceCompany"];
int[] Rowarray = new int[6] { 13, 21, 29, 37, 45, 53 };
for (int CompanyID = 1; CompanyID <= 6; CompanyID++) // 填充DataTable
{
range = datasheet.get_Range("D" + Rowarray[CompanyID - 1].ToString(), "K" + (Rowarray[CompanyID - 1]+5).ToString());
Cellarray = (System.Array)range.Value;
for (int InsuranceID = 1; InsuranceID <= 5; InsuranceID++)
{
DataRow newRow = dt.NewRow();
newRow["year"] = year;
newRow["month"] = month;
newRow["CompanyID"] = CompanyID;
newRow["InsuranceID"] = InsuranceID;
newRow["NewInsurancePremium"] = (Cellarray.GetValue(InsuranceID, 1)!= null ? Cellarray.GetValue(InsuranceID,1) : DBNull.Value);
newRow["RenewalPremium"] = (Cellarray.GetValue(InsuranceID, 3) != null ? Cellarray.GetValue(InsuranceID, 3) : DBNull.Value);
newRow["ExpenditureAndPayment"] = (Cellarray.GetValue(InsuranceID, 5) != null ? Cellarray.GetValue(InsuranceID, 5) : DBNull.Value);
newRow["GrossPremiumIncome"] = (Cellarray.GetValue(InsuranceID, 7) != null ? Cellarray.GetValue(InsuranceID, 7) : DBNull.Value);
dt.Rows.Add(newRow);
}
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn)) //用SqlBulkCopy将DataTable的表批量导入到数据源
{
bulkCopy.DestinationTableName =
"LifeInsuranceCompany";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
this.textBox1.Clear();
this.textBox1.Text+="数据导入失败!"+Environment.NewLine +ex;
}
}
}
else
{
this.textBox1.Clear();
this.textBox1.Text += "寿险公司" + year.ToString() + "年" + month.ToString() + "月的表已经存在,不需要再次导入!";
rdr.Close();
}
}
}
}