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("保存成功");