C#用NPOI读取Excel数据到数据库中行的顺序乱怎么办?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#用NPOI读取Excel数据到数据库中行的顺序乱怎么办?相关的知识,希望对你有一定的参考价值。
private void button4_Click(object sender, EventArgs e)
string filepath= @"D:\temp1.xlsx";
FileStream filestream = new FileStream(filepath, FileMode.OpenOrCreate,FileAccess.ReadWrite);
//filestream.Position=0;
XSSFWorkbook workbook = new XSSFWorkbook(filestream);
int sheetcount = workbook.Count;
if (sheetcount > 0)
var sheet = workbook.GetSheetAt(0);
for (int i = 1; i <= sheet.LastRowNum; i++)
IRow row = sheet.GetRow(i);
string tempname = Dqml(row,0);
string tempmm = Dqml(row,1);
sjvlj(tempname,tempmm);
void sjvlj(string a,string b)
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local);Initial Catalog=MF;User ID=sa;Pwd=P@ssw0rd";
conn.Open();
SqlTransaction sqltran = conn.BeginTransaction();
// textBox1.Text = a;
string sqlstring = string.Format("insert into table_4(yhm,mm) values('0','1')", a,b);
SqlCommand comm = new SqlCommand(sqlstring,conn);
comm.Transaction = sqltran;
int p = comm.ExecuteNonQuery();
sqltran.Commit();
comm.Dispose();
comm.Clone();
conn.Dispose();
conn.Close();
string Dqml(IRow row, int l)
if (row != null)
ICell cell = row.GetCell(l);
if (cell != null)
if (cell.CellType == CellType.String)
return cell.StringCellValue.Trim();
if (cell.CellType == CellType.Numeric)
return cell.NumericCellValue.ToString().Trim();
return cell.StringCellValue.Trim();
return string.Empty;
这里可以直接在vs程序中引入Spire.Xls.dll这一个dll程序集文件就可以实现数据的导入导出了。可以直接在NuGet中搜索安装,以下是导入excel数据到datatable的代码方法:
追问//创建Workbook对象并加载Excel文档
Workbook workbook = new Workbook();workbook.LoadFromFile(@"F:\\ExportData.xlsx" ,ExcelVersion.Version2013);
//获取第一张
sheetWorksheet sheet = workbook.Worksheets[0];
//设置range范围
CellRange range = sheet.Range[sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn];
//输出数据, 同时输出列名以及公式值
DataTable dt = sheet.ExportDataTable(range, true, true);
这个东西没有用过能不能给我一个完整的例子?我照葫芦画瓢一下。看嫩不嫩满足需求。
参考技术A 一、下载引用下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2007版需要此dll)。
二、excel转datatable类
[csharp] view
plain copy
using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
namespace NPOIOprateExcel
public class ExcelUtility
/// <summary>
/// 将excel导入到datatable
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = 0;
try
using (fs = File.OpenRead(filePath))
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(fs);
if (workbook != null)
sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null)
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
IRow firstRow = sheet.GetRow(0);//第一行
int cellCount = firstRow.LastCellNum;//列数
//构建datatable的列
if (isColumnName)
startRow = 1;//如果第一行是列名,则从第二行开始读取追问
你好!能不能把后面的代码也给我?这样做数据库表是顺序和Excel表里的顺序就一致了吗?我的错在哪里?
参考技术B你判断是否乱序是根据哪个字段,此字段是否自动增长?
如果没有自动增长字段,查询时候也没指定order by,那么sql本身也没保证顺序,属于正常现象
你在单个insert周围用了事务,没什么意义
我原来的Excel表里面是有日期,是连续的。但是按照我的方式导入到数据库中日期就不连续了。
追答那你select的时候oder by date即可
参考技术C 乱就乱了,数据库中行的顺序无所谓,反正用的时候order by一下就行了。NPOI读取Excel,导入数据到Excel练习01
NPOI 2.2.0.0,初级读取导入Excel
1.读取Excel,将数据绑定到dgv上
1 private void button1_Click(object sender, EventArgs e) 2 { 3 List<Book> books = new List<Book>(); 4 //1.读取Excel文件 5 using (FileStream fsReder = File.OpenRead("练习.xlsx")) 6 { 7 //2.创建工作簿 8 IWorkbook wk = new XSSFWorkbook("练习.xlsx"); 9 //IWorkbook wk=new XSSFWorkbook(fsReder); 10 //获取第一个工作表 11 ISheet sheet = wk.GetSheetAt(0); 12 //3.遍历每一行,行和列的索引都是从0开始 13 for (int i = 3; i < sheet.LastRowNum; i++) 14 { 15 IRow row = sheet.GetRow(i); 16 //MessageBox.Show(row.GetCell(0).ToString()); 17 //4.读取每一行的数据,加到对象中 18 books.Add(new Book() 19 { 20 Name = row.GetCell(0).ToString(), 21 One = row.GetCell(1).ToString(), 22 Two = row.GetCell(2).ToString(), 23 Three = row.GetCell(3).ToString(), 24 Four = row.GetCell(4).ToString(), 25 Five = row.GetCell(5).ToString(), 26 Six = row.GetCell(6).ToString(), 27 28 }); 29 } 30 } 31 //5.绑定数据 32 dgv.DataSource = books; 33 dgv.AutoGenerateColumns = false; 34 dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 35 MessageBox.Show("操作完成"); 36 }
2.将数据导入到Excel中
1 private void button2_Click(object sender, EventArgs e) 2 { 3 List<Book> books = new List<Book>() 4 { 5 new Book() {Name = "火影忍者",One ="34",Two = "56",Three = "67",Four = "78",Five = "99",Six = "54"}, 6 new Book() {Name = "海贼王", One ="64",Two = "79",Three = "97",Four = "74",Five = "29",Six = "56"}, 7 new Book() {Name = "死神",One ="94",Two = "51",Three = "57",Four = "64",Five = "90",Six = "74"}, 8 new Book() {Name = "游戏王",One ="94",Two = "30",Three = "56",Four = "45",Five = "58",Six = "46"}, 9 }; 10 //1.创建工作簿 11 using (FileStream fsWrite = File.OpenWrite("1.xlsx")) 12 { 13 IWorkbook wk = new XSSFWorkbook(); 14 //2.创建第一个工作表 15 ISheet sheet = wk.CreateSheet("第一张表"); 16 //第一行设置标题 17 IRow rowHead = sheet.CreateRow(0); 18 19 rowHead.CreateCell(0).SetCellValue("图书名"); 20 rowHead.CreateCell(1).SetCellValue("一月"); 21 rowHead.CreateCell(2).SetCellValue("二月"); 22 rowHead.CreateCell(3).SetCellValue("三月"); 23 rowHead.CreateCell(4).SetCellValue("四月"); 24 rowHead.CreateCell(5).SetCellValue("五月"); 25 rowHead.CreateCell(6).SetCellValue("六月"); 26 27 //3.在工作表的最后一行下,循环创建工作表的每一行,添加数据 28 for (int i = 1; i < books.Count; i++) 29 { 30 IRow row = sheet.CreateRow(i); 31 row.CreateCell(0).SetCellValue(books[i].Name); 32 row.CreateCell(1).SetCellValue(books[i].One); 33 row.CreateCell(2).SetCellValue(books[i].Two); 34 row.CreateCell(3).SetCellValue(books[i].Three); 35 row.CreateCell(4).SetCellValue(books[i].Four); 36 row.CreateCell(5).SetCellValue(books[i].Five); 37 row.CreateCell(6).SetCellValue(books[i].Six); 38 } 39 wk.Write(fsWrite); 40 } 41 42 MessageBox.Show("操作完成"); 43 }
以上是关于C#用NPOI读取Excel数据到数据库中行的顺序乱怎么办?的主要内容,如果未能解决你的问题,请参考以下文章