.Net 操作Excel表格

时间:2021-07-26 07:38:48

一、.从NuGet中,引用 Microsoft.Office.Interop.Excel类库。

方法一、先打开一个execl表然后进行保存

 Application xApp = null;
Workbook xBook = null; try
{
//1.创建Applicaton对象
xApp = new Application();
xApp.Visible = true; Workbooks wbs = xApp.Workbooks;
Workbook wb = wbs.Add(Missing.Value);
Worksheet xSheet = (Worksheet)wb.Worksheets["Sheet1"];
Range r = xSheet.get_Range("A1", "N1"); object[] objHeader =
{
"序号", "用户名", "手机号", "是否消费", "充值金额", "充值次数", "购买服务金额", "购买服务次数", "购买版权金额", "购买版权次数", "代金券金额",
"赠送金额", "总金额", "账户余额"
}; int row = ;//第一行是标题
for (int i = ; i < array.Length; i++)
{
var str = array[i];
var list = TJsonResult.DeserializeObject<List<UserInfoAnalysisEntity>>(str);
foreach (var entity in list)
{
if (entity.Cost == "是")
{
xSheet.Cells.Font.ColorIndex = ;
}
else
{
xSheet.Cells.Font.ColorIndex = ;
}
xSheet.Cells[row, ] = entity.Id;
xSheet.Cells[row, ] = entity.UserName;
xSheet.Cells[row, ] = entity.Phone;
xSheet.Cells[row, ] = entity.Cost;
xSheet.Cells[row, ] = entity.Recharge;
xSheet.Cells[row, ] = entity.RechargeNum;
xSheet.Cells[row, ] = entity.BuyServices;
xSheet.Cells[row, ] = entity.BuyServicesNum;
xSheet.Cells[row, ] = entity.BuyCopyRight;
xSheet.Cells[row, ] = entity.BuyCopyRightNum;
xSheet.Cells[row, ] = entity.Coupon;
xSheet.Cells[row, ] = entity.GiveMoney;
xSheet.Cells[row, ] = entity.TotalMoney;
xSheet.Cells[row, ] = entity.Balance;
row++;//表示行号
}
}

var filepath = AppDomain.CurrentDomain.BaseDirectory + "test123.xlsx";
           xSheet.SaveAs(filepath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
         Missing.Value, Missing.Value, Missing.Value, Missing.Value);


更多操作:https://www.cnblogs.com/junshijie/p/5292087.html

另一种方法是引用 Free Spire.XLS for .NET 这个类库 

https://www.cnblogs.com/Yesi/category/649975.html