C# WinForm导出Excel方法介绍
发布时间:2022-12-01 13:25:57
.NET开发人员首选的方法,通过COM组件调用Office软件本身来实现文件的创建和读写,但是数据量较大的时候异常缓慢;如下代码所示已经做了优化,将一个二维对象数组赋值到一个单元格区域中(下面的代码中只能用于导出列数不多于26列的数据导出):
Office PIA
public static void ExportToExcel(DataSet dataSet, string outputPath)
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
int sheetIndex = 0;
foreach (System.Data.DataTable dt in dataSet.Tables)
{
object[,] data = new object[dt.Rows.Count + 1, dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
data[0, j] = dt.Columns[j].ColumnName;
}
for (int j = 0; j < dt.Columns.Count; j++)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
data[i + 1, j] = dt.Rows[i][j];
}
}
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (dt.Columns.Count > colCharsetLen)
{
finalColLetter = colCharset.Substring(
(dt.Columns.Count - 1) / colCharsetLen - 1, 1);
}
finalColLetter += colCharset.Substring(
(dt.Columns.Count - 1) % colCharsetLen, 1);
Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets.Add(
workbook.Sheets.get_Item(++sheetIndex),
Type.Missing, 1, Excel.XlSheetType.xlWorksheet);
sheet.Name = dt.TableName;
string range = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
sheet.get_Range(range, Type.Missing).Value2 = data;
((Excel.Range)sheet.Rows[1, Type.Missing]).Font.Bold = true;
}
workbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
excel.Quit();
KillSpecialExcel(excel);
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
static void KillSpecialExcel(Excel.Application app)
{
try
{
if (app != null)
{
int processId;
GetWindowThreadProcessId(new IntPtr(app.Hwnd), out processId);
System.Diagnostics.Process.GetProcessById(processId).Kill();
}
}
catch (Exception ex)
{
throw ex;
}
}
文件流
这种方法的效率明显高于第一种,而且也不需要安装Office,但是导出的xls文件并不符合Excel的格式标准,在打开生成的xls文件时会提示:The file you are trying to open is in a different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file.
public static void ExportToExcel(System.Data.DataSet ds, string path)
{
StreamWriter sw = null;
try
{
long totalCount = ds.Tables[0].Rows.Count;
sw = new StreamWriter(path, false, Encoding.Unicode);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
sb.Append(ds.Tables[0].Columns[i].ColumnName + "\t");
}
sb.Append(Environment.NewLine);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
sb.Append(ds.Tables[0].Rows[i][j].ToString() + "\t");
}
sb.Append(Environment.NewLine);
}
sw.Write(sb.ToString());
sw.Flush();
}
catch (IOException ioe)
{
throw ioe;
}
finally
{
if (sw != null)
{
sw.Close();
}
}
}


猜你喜欢
- Volatile关键字的作用主要有如下两个:1.线程的可见性:当一个线程修改一个共享变量时,另外一个线程能读到这个修改的值。2. 顺序一致性
- Java Hutool 包工具类推荐 ExcelUtil包引入hutool包版本号可根据实际情况更换<dependency> &
- 一、简介1.Apollo 是什么?Apollo(阿波罗)是携程框架部门研发的分布式配置中心。服务端基于Spring Boot和Spring
- switchJava7开始,switch的参数可以是String类型了,这真的是一个很有用的改进,毕竟string还是挺常用的。到目前为止,
- activity_main.xml中的配置<LinearLayout xmlns:android="http://schem
- Java停止线程的逻辑(协同、通知)在Java程序中,我们想要停止一个线程可以通过interrupt方法进行停止。但是当我们调用interr
- 简介由于最近的项目需求,需要在把配置类导入到容器中,通过查询,使用@Import注解就能实现这个功能,@Import注解能够帮我们吧普通配置
- 实例描述现有某班学生的两份成绩,两份成绩中存在一些不一致的记录。需借助于编程方法找出这些不一致的记录。实例代码using System;us
- 因为案例比较简单,所以简单用AndroidApplication -> Game -> Stage 搭建框架 一、主入口,无特殊
- file: BluetoothEventLoop.java GB/GB2/GB3: 1. import android.os.PowerMa
- 前言 因为自己在做的一个小软件里面需要用到从A-Z排序的ListView,所以自然而然的想到了微信的联系人,我想要的就是那样的效果。本来没
- 前言周六在公司写Reactor模型,一女同事问我为啥都2023年了还在学习Reactor模型呀,我问她为啥快30的年纪了,周六还在公司看我写
- 首先struts上传最大大小由两个地方决定. · struts.multipart.maxSize决定整个post的form最大是
- using System;using System.Collections.Generic;using System.IO;using Sy
- 本文实例为大家分享了Android实现语音播放与录音的具体代码,供大家参考,具体内容如下项目用到的技术点和亮点语音录音 (单个和列表)语音播
- 1、unity的脚本模板新版本unity中的C#脚本有三类,第一类是我们平时开发用的C# Script;第二类是Testing,用来做单元测
- 目录一.什么是负载均衡二.负载均衡的简单分类三.为什么需要做负载均衡四.springCloud如何开启负载均衡五.IRule1.Random
- 1.搜索树的概念二叉搜索树是一种特殊的二叉树,又称二叉查找树,二叉排序树,它有几个特点:如果左子树存在,则左子树每个结点的值均小于根结点的值
- 常见尺寸单位Android开发中的常用尺寸单位有如下几种:dp (dip)pxptinchsp算不知道确切含义,相信对于以上这几种尺寸单位大
- 基础知识介绍: @RequestBody主要用来接收前端传递给后端的json字符串中的