C# 使用Microsoft.Office.Interop.Excel.Application对 Excel创建、写入

System.Reflection.Missing miss = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

excel.Application.Workbooks.Add(true);

excel.Visible = false;

if (excel == null)

{

MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;

Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)books.Add(miss);

Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;

sheet.Name = "Sheet";//工作薄名称

//填充列头

for (int i = 0; i < tb_result.Columns.Count; i++)

{

excel.Cells1, i + 1 = tb_result.Columnsi.ColumnName;

}

//填充数据

for (int row = 0; row <= tb_result.Rows.Count - 1; row++)

{

for (int column = 0; column < tb_result.Columns.Count; column++)

{

//excel.Cellsrow + 2, column + 1.AutoFit();

//if (tb_result.Rowsrowcolumn.GetType() == typeof(string))

try

{

Convert.ToInt32(tb_result.Rowsrowcolumn.ToString().Trim());

excel.Cellsrow + 2, column + 1.NumberFormatLocal = "@";

excel.Cellsrow + 2, column + 1 = tb_result.Rowsrowcolumn.ToString();

}

catch

{

excel.Cellsrow + 2, column + 1 = tb_result.Rowsrowcolumn.ToString();

}

//宽度

excel.Cellsrow + 2, column + 1.ColumnWidth = tb_result.Rowsrowcolumn.ToString().Length*1.5;

if (tb_result.Rowsrowcolumn.ToString().Length == 0)

{

excel.Cellsrow + 2, column + 1.ColumnWidth = tb_result.Columnscolumn.ColumnName.Length * 1.5;

}

}

}

string Version = excel.Version;

int FormatNum;

if (Convert.ToDouble(Version) < 12)

{

FormatNum = -4143;

}

else

{

FormatNum = 56;

}

sheet.SaveAs(filepath, FormatNum, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);

book.Close(false, miss, miss);

books.Close();

excel.Quit();

System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);

System.Runtime.InteropServices.Marshal.ReleaseComObject(book);

System.Runtime.InteropServices.Marshal.ReleaseComObject(books);

System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

GC.Collect();

相关推荐
鬼手点金38 分钟前
模型即 Agent:当模型本身成为产品
开发语言·前端·人工智能·python·机器学习
kiracrimson1 小时前
npm 入门:包管理器、依赖与 npx
前端·npm·node.js
ShineWinsu1 小时前
对于JavaScript:初识JavaScript以及输入输出
java·开发语言·前端·javascript·css·面试·html
鲤鱼_5991 小时前
教培机构一体化运营管理系统操作手册
前端
鶴哥只手遮天1 小时前
React 19.3.1 源码深度剖析-第 3 章 Fiber 架构与双缓冲
前端·react.js·开源
鶴哥只手遮天1 小时前
React 19.3.1 源码深度剖析-第 9 章(下)lazy、retry、hydration 与实战
前端·react.js·开源
鶴哥只手遮天1 小时前
React 19.3.1 源码深度剖析-第 6 章 React DOM 渲染器与 Commit 阶段(把 Fiber 副作用落到真实 DOM)(上)
前端·react.js·开源
鶴哥只手遮天1 小时前
React 19.3.1 源码深度剖析-第 6 章 React DOM 渲染器与 Commit 阶段(把 Fiber 副作用落到真实 DOM)(下)
前端·react.js·开源