一:借助免费版Spire.XLS实现数据导入
spire.xls安装使用方法参考链接:https://www.cnblogs.com/zengpeng/p/10832368.html
推荐使用Nuget安装方法,直接nuget
using System.Data;
using Spire.Xls;
//excel_i参数设置的目的是为了向excel中追加数据
public void writeExcel_ij(string filepath,string filename,string time,string opertion,int excel_i)
{
//创建一个Workbook对象
Workbook workbook = new Workbook();
//加载一个现有的Excel文档
workbook.LoadFromFile(@filepath);
//获取第一张工作表
Worksheet sheet = workbook.Worksheets[0];
//定义一个DataTable,写入数据(也可以直接从数据库获取DataTable)
DataTable datatable = new DataTable();
datatable.Columns.Add("文件名");
datatable.Columns.Add("响应时间");
datatable.Columns.Add("操作");
datatable.Rows.Add(new string[] { filename, time, opertion });
//从第excel_i行第1列开始插入数据,true代表数据包含列名
sheet.InsertDataTable(datatable, true, excel_i, 1);
//保存文件
workbook.SaveToFile(filepath, ExcelVersion.Version2013);
}
//将数据写入已存在Excel
public static void writeExcel(string result, string filepath)
{
//1.创建Applicaton对象
Microsoft.Office.Interop.Excel.Application xApp = new
Microsoft.Office.Interop.Excel.Application();
//2.得到workbook对象,打开已有的文件
Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks.Open(filepath,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//3.指定要操作的Sheet
Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
//在第一列的左边插入一列 1:第一列
//xlShiftToRight:向右移动单元格 xlShiftDown:向下移动单元格
Range Columns = (Range)xSheet.Columns[1, System.Type.Missing];
Columns.Insert(XlInsertShiftDirection.xlShiftDown, Type.Missing);
//4.向相应对位置写入相应的数据
//xSheet.Cells[Column(列)][Row(行)] = result;
xSheet.Cells[1][1] = result;
//5.保存保存WorkBook
xBook.Save();
//6.从内存中关闭Excel对象
xSheet = null;
xBook.Close();
xBook = null;
//关闭EXCEL的提示框
xApp.DisplayAlerts = false;
//Excel从内存中退出
xApp.Quit();
xApp = null;
}