您的位置:首页 > 数据库

EXcel 导入数据库和导出数据库的代码

2012-09-19 22:09 369 查看
首先导入NPOI这个程序集

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 NPOI;//导入的程序集

using Ionic;

using NPOI.HSSF.UserModel;

using System.IO;

using NPOIs.BLL;

using NPOIs.Model;

namespace NPOIs

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

导出数据库

private void button1_Click(object sender, EventArgs e)

{

using (FileStream str = new FileStream(@"F:\Book.xls", FileMode.Open, FileAccess.Read))

{

HSSFWorkbook workkbook = new HSSFWorkbook(str);

HSSFSheet sheet = workkbook.GetSheetAt(0) as HSSFSheet;

for (int i = 1; i < sheet.LastRowNum; i++)

{

HSSFRow row = sheet.GetRow(i) as HSSFRow;

TBook book = new TBook();

book.ISBN = row.GetCell(0).StringCellValue;

book.BookName = row.GetCell(1).StringCellValue;

book.Athor = row.GetCell(2).StringCellValue;

book.Publisher = row.GetCell(3).StringCellValue;

book.Price = row.GetCell(4).NumericCellValue;

book.CNum = (int)row.GetCell(5).NumericCellValue;

book.SNum = (int)row.GetCell(6).NumericCellValue;

book.BookPhoto = row.GetCell(7).StringCellValue;

int t = new TBookBLL().AddNew(book);

}

MessageBox.Show("添加成功!");

}

}

//导入数据库

private void button2_Click(object sender, EventArgs e)

{

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;

List<TBook> list = new List<TBook>();

list = new TBookBLL().ListAll() as List<TBook>;

for (int i = 0; i < list.Count; i++)

{

HSSFRow row = sheet.CreateRow(i) as HSSFRow;

row.CreateCell(0).SetCellValue(list[i].ISBN);

row.CreateCell(1).SetCellValue(list[i].BookName);

row.CreateCell(2).SetCellValue(list[i].Athor);

row.CreateCell(3).SetCellValue(list[i].Publisher);

row.CreateCell(4).SetCellValue((double)list[i].Price);

row.CreateCell(5).SetCellValue((double)list[i].CNum);

row.CreateCell(6).SetCellValue((double)list[i].SNum);

row.CreateCell(7).SetCellValue(list[i].BookPhoto);

}

FileStream stream = new FileStream(@"F:\TBOOK.xls", FileMode.OpenOrCreate, FileAccess.Write);

workbook.Write(stream);

stream.Dispose();

MessageBox.Show("导入成功!");

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: