借助于SQL。代码如下:
using System;using SystemCollectionsGeneric;
using SystemLinq;
using SystemText;
using SystemWindowsForms;
using SystemDiagnostics;
using SystemIO;
//using MicrosoftOfficeInteropExcel;
using SystemDataOleDb;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
namespace ClothingSales_0_5
{
public class Import
{
//private string fileName;
/// <summary>
/// 将DataGridView中数据导入到Excel
/// </summary>
/// <param name="dgv">DataGridView的名称</param>
public bool getExcel(DataGridView dgv,Label lbl)
{
bool fflag = true;
OpenFileDialog open = new OpenFileDialog();
openTitle = "请选择要导入的Excel文件";
openFilter = "Excel文件(xls)|xls";
if (openShowDialog() == DialogResultOK)
{
string fileName = openFileName;
//根据路径打开一个Excel文件并将数据填充到DataSet中
string strConn = "Provider=MicrosoftJetOLEDB40;Data Source = " + fileName + ";Extended Properties ='Excel 80;HDR=NO;IMEX=1'";//导入时包含Excel中的第一行数据,并且将数字和字符混合的单元格视为文本进行导入
OleDbConnection conn = new OleDbConnection(strConn);
connOpen();
string strExcel = "select from [sheet1$]";
OleDbDataAdapter comm = new OleDbDataAdapter(strExcel, strConn);
DataSet ds = new DataSet();
try
{
commFill(ds, "table1");
}
catch
{
MessageBoxShow("错误信息:009", "错误");
}
commFill(ds, "table1");
//根据DataGridView的列构造一个新的DataTable
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
foreach (DataGridViewColumn dgvc in dgvColumns)
{
if (dgvcVisible)
{
DataColumn dc = new DataColumn();
dcColumnName = dgvcDataPropertyName;
dtColumnsAdd(dc);
DataColumn dc2 = new DataColumn();
dc2ColumnName = dgvcDataPropertyName;
dt2ColumnsAdd(dc2);
if (dgvcCellType == typeof(DataGridViewCheckBoxCell))
{
dc2DataType = TypeGetType("SystemBoolean");
}
}
}
//根据Excel的行逐一对上面构造的DataTable的列进行赋值
foreach (DataRow excelRow in dsTables[0]Rows)
{
int i = 0;
DataRow dr = dtNewRow();
foreach (DataColumn dc in dtColumns)
{
dr[dc] = excelRow[i];
i++;
}
dtRowsAdd(dr);
}
//判断Excel的格式是否正确
int n = 0;
for (int j = 0; j < dtColumnsCount; j++)
{
bool flag = false;
for (int k = n; k < dgvColumnCount; k++)
{
if (dgvColumns[k]Visible) //隐藏的列
{
if (dgvColumns[k]HeaderTextTrim()ToString() == dtRows[0][j]ToString())
{
if (dgvColumns[k]CellType == typeof(DataGridViewCheckBoxCell))
{
//listAdd(j);
//num++;
}
flag = true;
n = k + 1;
break;
}
}
}
if (flag == false)
{
MessageBoxShow("导入的Excel的格式错误", "提示");
fflag = false;
return fflag;
}
}
//删除多余的行
int rowCount = (dtRowsCount) / 2;
for (int i = 0; i <= rowCount; i++)
{
dtRowsRemoveAt(0);
}
//处理Boolean类型的数据
for (int i = 0; i < dtRowsCount; i++)
{
DataRow dr = dt2NewRow();
for (int j = 0; j < dtColumnsCount; j++)
{
try
{
dr[j] = dtRows[i][j];
}
catch
{
dr[j] = false;
}
}
dt2RowsAdd(dr);
}
//导入到dataGridView
dgvDataSource = dt2;
lblText = dgvRowCountToString();
}
else
{
fflag = false;
}
return fflag;
}
}
}
以上就是关于将excel数据导入到datagridview中全部的内容,包括:将excel数据导入到datagridview中、、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)