1.在NuGet管理包中搜索:Microsoft.Office.Interop.Excel,如下图红色标记处所示,进行安装
2. 安装完成后,在程序中引入命名空间如下所示:
using Microsoft.Office.Interop.Excel; //第一步 添加excel第三方库
using Application = Microsoft.Office.Interop.Excel.Application; //声明excel
3. 创建一个excel文档并在指定位置写入数据,示例代码:
// 创建Excel对象
Application app = new Application();
Workbook workbook = app.Workbooks.Add();
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
// 设置单元格内容
for (int i = 0; i < bytes.Length/2; i++)
{
byte[] tempArray = new byte[2];
int length = Math.Min(2, bytes.Length-i );
Array.Copy(bytes, i, tempArray, 0, length);
worksheet.Cells[1, i+2] = BitConverter.ToString(tempArray).Replace("-", " "); //核心代码,设置单元格横纵坐标(都是从1开始)显示内容,可自行更换测试
}
Microsoft.Office.Interop.Excel.Borders borders = null; //设置边框
Microsoft.Office.Interop.Excel.Range range = worksheet.Range["A1:" + "J54"]; //设定外框线绘制区域
borders = range.Borders; //绘制边框
borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; //设置线条样式
borders.Weight = 2d;//设置线条宽度
range.HorizontalAlignment = XlHAlign.xlHAlignCenter; //设置文本居中方式
worksheet.Columns.EntireColumn.AutoFit(); //设置表格内容根据文本自适应
workbook.SaveAs("C:\\Users\\Administrator\\Desktop\\222.xlsx"); // 保存Excel文件
workbook.Close();// 关闭Excel对象
app.Quit();// 关闭软件
MessageBox.Show("保存成功");