=============================================================asp.net========================================
num = Convert.ToInt32(ini.IniReadValue("Record", "Num").ToString());
num ;
Random random = new Random();
//保存文件的虚拟路径
string path = "UploadFile/";
//获取选择的文件名
string fileName = FileUpload1.FileName;
///文件名称判断
if (true)
{
}
//获取文件扩展名称
string fileExt = Path.GetExtension(fileName);
//生成新文件名
//string newName ="Mes" DateTime.Now.ToString("yyyyMMddHHmmssfff") random.Next(0, 9999).ToString();
string NewName = "MES" DateTime.Now.ToString("yyyyMMdd") num.ToString();
ini.IniWriteValue("Record", "Num", num.ToString());
//获取指定虚机路径的物理路径
string fullPath = HttpContext.Current.Server.MapPath(path);
//上传文件保存路径
string savePath = fullPath NewName fileExt;
//保存文件到服务器
FileUpload1.SaveAs(savePath);
==================================================================Winform=================================================
/// <summary>
/// 浏览
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bn_MConfig_Click(object sender, EventArgs e)
{
this.openFileDialog1.Filter = "所有文件(*.*)|*.*";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
/*
string PicFileName = this.openFileDialog1.FileName;
this.imgList.Add(PicFileName);
this.imageList1.Images.Add(Image.FromFile(PicFileName));
*/
string FileName = this.openFileDialog1.FileName;
tb_file.Text = FileName;
}
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="openFileDialog"></param>
/// <param name="FileTypeName"></param>
public static void FileUp(OpenFileDialog openFileDialog, string FileTypeName)
{
try
{
//FileTypeName = "Models";
Random random = new Random();
//保存文件的虚拟路径
string path = "UploadFile//" FileTypeName "//";
//获取选择的文件名
string fileName = openFileDialog.FileName;
///文件名称判断
if (true)
{
}
//获取文件扩展名称
string fileExt = Path.GetExtension(fileName);
//生成新文件名
//string newName ="Mes" DateTime.Now.ToString("yyyyMMddHHmmssfff") random.Next(0, 9999).ToString();
string NewName = FileTypeName DateTime.Now.ToString("yyyyMMddHHmmssfff");
//获取指定虚机路径的物理路径
string fullPath = Path.GetDirectoryName(path);
fullPath = Path.GetFullPath(path);
//上传文件保存路径
string savePath = fullPath NewName fileExt;
//DBHelpter.MsgBox(savePath);
//保存文件到本地
File.Copy(fileName, savePath);
///获取execl数据
//返回指定目录中的文件的名称(绝对路径)
string[] files = System.IO.Directory.GetFiles(fullPath);
//获取Test文件夹下所有文件名称
string[] files2 = System.IO.Directory.GetFiles(@fullPath, "*", System.IO.SearchOption.AllDirectories);
////获取指定目录下面指定格式的所有文件
//DirectoryInfo di = new DirectoryInfo(@fullPath.TrimEnd(‘\‘));
//FileInfo[] files1 = new string[] { "*.xlsx", "*.csv", "*.xls" }.SelectMany(i => di.GetFiles(i, SearchOption.AllDirectories)).Distinct().ToArray();
List<long> MESNO = new List<long>();
List<string> FilePathlist = GetFiles(new DirectoryInfo(fullPath), "*.xlsx,*.xls");
for (int i = 0; i < FilePathlist.Count(); i )
{
string str = FilePathlist[i].Split(‘.‘)[0];
string[] sArray = str.Split(new string[] { FileTypeName }, StringSplitOptions.RemoveEmptyEntries);
long NO = Convert.ToInt64(sArray[2]);
MESNO.Add(NO);
}
long max = 0;
for (int i = 0; i < MESNO.Count(); i )
{
max = MESNO[0];
if (MESNO[i] > max)
{
max = MESNO[i];
}
}
string LastFileName = fullPath FileTypeName max fileExt;
FileSvr fileSvr = new FileSvr();
///有Office配置文件
//DataTable dt = fileSvr.GetExcelDatatable(LastFileName, "mapTable");
///引用NPIO
string msgstr = "";
DataSet ds = NPIOClass.ExcelToDataSet(LastFileName, msgstr);
string name = "";
for (int i = 0; i < ds.Tables.Count; i )
{
name = ds.Tables[i].TableName ",";
int num= InsertDatas(ds.Tables[i]);
if (num>0)
{
MessageBox.Show("上传成功!");
}
else
{
MessageBox.Show("上传失败!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Physical_planning_system.UploadClass
{
public class NPIOClass
{
/// <summary>
/// Excel转换成DataTable(.xls)
/// </summary>
/// <param name="filePath">Excel文件路径</param>
/// <returns></returns>
public static DataTable ExcelToDataTable(string filePath)
{
var dt = new DataTable();
using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var hssfworkbook = new XSSFWorkbook(file);
var sheet = hssfworkbook.GetSheetAt(0);
for (var j = 0; j < 5; j )
{
dt.Columns.Add(Convert.ToChar(((int)‘A‘) j).ToString());
}
var rows = sheet.GetRowEnumerator();
while (rows.MoveNext())
{
var row = (HSSFRow)rows.Current;
var dr = dt.NewRow();
for (var i = 0; i < row.LastCellNum; i )
{
var cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
switch (cell.CellType)
{
case CellType.Blank:
dr[i] = "[null]";
break;
case CellType.Boolean:
dr[i] = cell.BooleanCellValue;
break;
case CellType.Numeric:
dr[i] = cell.ToString();
break;
case CellType.String:
dr[i] = cell.StringCellValue;
break;
case CellType.Error:
dr[i] = cell.ErrorCellValue;
break;
case CellType.Formula:
try
{
dr[i] = cell.NumericCellValue;
}
catch
{
dr[i] = cell.StringCellValue;
}
break;
default:
dr[i] = "=" cell.CellFormula;
break;
}
}
}
dt.Rows.Add(dr);
}
}
return dt;
}
/// <summary>
/// Excel转换成DataSet(.xlsx/.xls)
/// </summary>
/// <param name="filePath">Excel文件路径</param>
/// <param name="strMsg"></param>
/// <returns></returns>
public static DataSet ExcelToDataSet(string filePath, string strMsg)
{
strMsg = "";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string fileType = Path.GetExtension(filePath).ToLower();
string fileName = Path.GetFileName(filePath).ToLower();
try
{
ISheet sheet = null;
int sheetNumber = 0;
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
if (fileType == ".xlsx")
{
// 2007版本
XSSFWorkbook workbook = new XSSFWorkbook(fs);
sheetNumber = workbook.NumberOfSheets;
for (int i = 0; i < sheetNumber; i )
{
string sheetName = workbook.GetSheetName(i);
sheet = workbook.GetSheet(sheetName);
if (sheet != null)
{
dt = GetSheetDataTable(sheet, strMsg);
if (dt != null)
{
dt.TableName = sheetName.Trim();
ds.Tables.Add(dt);
}
else
{
//MessageBox.Show("Sheet数据获取失败,原因:" strMsg);
}
}
}
}
else if (fileType == ".xls")
{
// 2003版本
HSSFWorkbook workbook = new HSSFWorkbook(fs);
sheetNumber = workbook.NumberOfSheets;
for (int i = 0; i < sheetNumber; i )
{
string sheetName = workbook.GetSheetName(i);
sheet = workbook.GetSheet(sheetName);
if (sheet != null)
{
dt = GetSheetDataTable(sheet, strMsg);
if (dt != null)
{
dt.TableName = sheetName.Trim();
ds.Tables.Add(dt);
}
else
{
// MessageBox.Show("Sheet数据获取失败,原因:" strMsg);
}
}
}
}
return ds;
}
catch (Exception ex)
{
strMsg = ex.Message;
return null;
}
}
/// <summary>
/// 获取sheet表对应的DataTable
/// </summary>
/// <param name="sheet">Excel工作表</param>
/// <param name="strMsg"></param>
/// <returns></returns>
private static DataTable GetSheetDataTable(ISheet sheet, string strMsg)
{
strMsg = "";
DataTable dt = new DataTable();
string sheetName = sheet.SheetName;
int startIndex = 0;// sheet.FirstRowNum;
int lastIndex = sheet.LastRowNum;
//最大列数
int cellCount = 0;
IRow maxRow = sheet.GetRow(0);
for (int i = startIndex; i <= lastIndex; i )
{
IRow row = sheet.GetRow(i);
if (row != null && cellCount < row.LastCellNum)
{
cellCount = row.LastCellNum;
maxRow = row;
}
}
//列名设置
try
{
for (int i = 0; i < maxRow.LastCellNum; i )//maxRow.FirstCellNum
{
//dt.Columns.Add(Convert.ToChar(((int)‘A‘) i).ToString());
dt.Columns.Add(maxRow.Cells[i].ToString());
//DataColumn column = new DataColumn("Column" (i 1).ToString());
//dt.Columns.Add(column);
}
}
catch
{
strMsg = "工作表" sheetName "中无数据";
return null;
}
//数据填充
for (int i = startIndex 1; i <= lastIndex; i )
{
IRow row = sheet.GetRow(i);
DataRow drNew = dt.NewRow();
if (row != null)
{
for (int j = row.FirstCellNum; j < row.LastCellNum; j)
{
if (row.GetCell(j) != null)
{
ICell cell = row.GetCell(j);
switch (cell.CellType)
{
case CellType.Blank:
drNew[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58)
drNew[j] = cell.DateCellValue;
else
drNew[j] = cell.NumericCellValue;
if (cell.CellStyle.DataFormat == 177 || cell.CellStyle.DataFormat == 178 || cell.CellStyle.DataFormat == 188)
drNew[j] = cell.NumericCellValue.ToString("#0.00");
break;
case CellType.String:
drNew[j] = cell.StringCellValue;
break;
case CellType.Formula:
try
{
drNew[j] = cell.NumericCellValue;
if (cell.CellStyle.DataFormat == 177 || cell.CellStyle.DataFormat == 178 || cell.CellStyle.DataFormat == 188)
drNew[j] = cell.NumericCellValue.ToString("#0.00");
}
catch
{
try
{
drNew[j] = cell.StringCellValue;
}
catch { }
}
break;
default:
drNew[j] = cell.StringCellValue;
break;
}
}
}
}
dt.Rows.Add(drNew);
}
return dt;
}
}
}
/// <summary>
/// 获取某种类型文件
/// </summary>
/// <param name="directory"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static List<string> GetFiles(DirectoryInfo directory, string pattern)
{
List<string> Filelist = new List<string>();
if (directory.Exists || pattern.Trim() != string.Empty)
{
string[] ext = pattern.Split(‘,‘);
for (int i = 0; i < ext.Count(); i )
{
foreach (FileInfo info in directory.GetFiles(ext[i]))
{
if (Filelist.Contains(info.FullName.ToString()))
{
continue;
}
Filelist.Add(info.FullName.ToString());
}
foreach (DirectoryInfo info in directory.GetDirectories())
{
GetFiles(info, pattern);
}
}
}
return Filelist;
}