简介:
作为一个刚刚入门的小白,在这里整理一些自己写过的代码,因为时间比较久远大多数的代码没有能找到出处,如果有用过你们代码,请联系我QQ:1206062480;我会表明出处。
NPOI导出excel
public ActionResult ExportExcelRun(DeviceOperationRecordSearch searchParms)
{
try
{
#region 获取数据
var db = new Context();
IQueryable<DeviceOperationRecord> deviceQuery = db.DeviceOperationRecord.Include(p => p.Device);
if (!searchParms.DeviceNo.IsNullOrEmpty())
{
deviceQuery = deviceQuery.Where(p => p.Device.DeviceNo == searchParms.DeviceNo);
}
if (searchParms.StartTime != null)
{
deviceQuery = deviceQuery.Where(p => p.StartTime >= searchParms.StartTime);
}
if (searchParms.EndTime != null)
{
deviceQuery = deviceQuery.Where(p => p.EndTime <= searchParms.EndTime);
}
deviceQuery = deviceQuery.OrderByDescending(x => x.StartTime);
var resList = deviceQuery.ToList();
#endregion
IWorkbook wb;
var path = AppDomain.CurrentDomain.BaseDirectory + @"Export\";
var dif = new DirectoryInfo(path);
if (!dif.Exists)
dif.Create();
var name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
string savePath = path + name;
string extension = Path.GetExtension(savePath);
//根据指定的文件格式创建对应的类
string excelTempPath = AppDomain.CurrentDomain.BaseDirectory + @"File\Excel.xlsx";
//读取Excel模板
using (FileStream fs = new FileStream(excelTempPath, FileMode.Open, FileAccess.Read))
{
//根据指定的文件格式创建对应的类
if (extension.Equals(".xls"))
{
wb = new HSSFWorkbook(fs);
}
else
{
wb = new XSSFWorkbook(fs);
}
}
ISheet sheet1 = wb.GetSheet("Run");
for (int i = 0; i < resList.Count; i++)
{
//for (int j = 1; j < 5; j++)
//{
// if (sheet1.GetRow(i + 3) == null || sheet1.GetRow(i + 3).ToString() == string.Empty)
// {
// ICell cell = sheet1.GetRow(i + 3).CreateCell(j, CellType.String);
// cell.SetCellValue("");
// }
//}
sheet1.GetRow(i + 3).GetCell(1).SetCellValue(resList[i].Device.DeviceNo);
sheet1.GetRow(i + 3).GetCell(2).SetCellValue(resList[i].Device.DeviceName);
sheet1.GetRow(i + 3).GetCell(3).SetCellValue(Convert.ToDateTime(resList[i].StartTime).ToString("yyyy-MM-dd HH:mm:ss"));
sheet1.GetRow(i + 3).GetCell(4).SetCellValue(Convert.ToDateTime(resList[i].EndTime).ToString("yyyy-MM-dd HH:mm:ss"));
}
using (FileStream fs = System.IO.File.OpenWrite(savePath))
{
wb.Write(fs);//向打开的这个Excel文件中写入表单并保存。
fs.Close();
}
return Json2(new JsonOkay());
}