|
#region 数据批量导入
protected string SaveTempFiels(FineUI.FileUpload fuload)
{
string strFileName = fuload.FileName.ToString();
string strFilePath = "";
strFileName = strFileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
strFileName = "StudentBaseInfo_" + DateTime.Now.Ticks.ToString() + "_" + strFileName;
strFilePath = "~/UpFiles/TempFiles/" + strFileName;
strFilePath = Server.MapPath(strFilePath);
fuload.SaveAs(strFilePath);
//fuload.Reset();
return @strFilePath;
}
protected DataTable ExcelToDataTable(string excelFilePath)
{
if (File.Exists(excelFilePath))
{
using (FileStream stream = File.OpenRead(excelFilePath))
{
HSSFWorkbook workbook = new HSSFWorkbook(stream);
HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
DataTable table = new DataTable();
table.TableName = "导入信息";
HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
{
// 如果遇到第一个空列,则不再继续向后读取
cellCount = i + 1;
break;
}
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
HSSFRow row = (HSSFRow)sheet.GetRow(i);
if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "")
{
// 如果遇到第一个空行,则不再继续向后读取
break;
}
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
dataRow[j] = row.GetCell(j);
}
table.Rows.Add(dataRow);
}
stream.Close();
workbook = null;
sheet = null;
return table;
}
}
else
{
return null;
}
}
protected DataSet ValidateUserTable(DataTable dt)
{
// 如果除表头外有数据
if (dt.Rows.Count > 0)
{
DataSet ds = new DataSet();
bool isCorrect = false;
string strDrValue = ""; /// 值
string strFieldName = ""; /// 字段名
string strMessage = ""; /// 错误信息
string[] arrstrList = new string[] { "", "" };
DataTable dtTable = new DataTable(); // 错误信息表
dtTable.Columns.Add("错误行号", typeof(string));
dtTable.Columns.Add("原数据", typeof(string));
dtTable.Columns.Add("错误信息", typeof(string));
#region 验证各列的值
// 遍历行
for (int i = 0; i < dt.Rows.Count; i++) // i=0 为表头
{
DataRow dr = dt.Rows[i];
for (int j = 0; j < dt.Columns.Count; j++)
{
isCorrect = true;
strDrValue = dr[j].ToString().Trim();
strFieldName = dt.Columns[j].ToString().Trim();
#region 遍历列并进行验证
switch (j)
{...}
}
}
#endregion
dt.TableName = "导入信息";
ds.Tables.Add(dt);
if (dtTable.Rows.Count>0)
{
dtTable.TableName = "错误信息";
ds.Tables.Add(dtTable);
}
return ds;
}
else
{
return null;
}
} |
|