问题一:Excel表格数据导入
解决办法:
简明扼要,直接粘贴代码
....此处省略代码万万行....
list.Add("create table [" + user + "ZJWEEKPLAN]" + "(cinvcode nvarchar(200)");
SqlDBHelper.ExecuteSqlTran(list);
string str = "", resultFile = "";
System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
openFileDialog1.InitialDirectory = "C:";//打开C盘
openFileDialog1.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003工作簿(*.xls)|*.xls";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
resultFile = openFileDialog1.FileName;//获取到文件名
}
if (!string.IsNullOrEmpty(resultFile))
{
DataTable dt = ExcelHelper.ReadFromExcel(resultFile);//写到中间表
}
public static string restosql = "";
public static void DataTableToSQLServer(DataTable dt, string connectString, string tableName)
{
string connectionString = connectString;
using (SqlConnection destinationConnection = new SqlConnection(connectionString))
{
destinationConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
try
{
bulkCopy.DestinationTableName = tableName;//要插入的表的表名
bulkCopy.BatchSize = dt.Rows.Count;
bulkCopy.ColumnMappings.Add("产品编码", "cinvcode");//映射字段名 DataTable列名 ,数据库 对应的列名
bulkCopy.WriteToServer(dt);
restosql = "success";
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("提示:"+ex.Message,"提示");
}
}
}
问题二:表格里面删除了行,看起来空白没数据。。导入做了空白校验报错
解决办法:去除空行。将刚刚导入好的DT表格走一遍这个方法
/// <summary>
/// 移除空行
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
protected DataTable RemoveEmpty(DataTable dt)
{
List<DataRow> removelist = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool rowdataisnull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
rowdataisnull = false;
}
}
if (rowdataisnull)
{
removelist.Add(dt.Rows[i]);
}
}
//移除空行
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
return dt;
}