


This article mainly introduces C# to implement hundreds of thousands of data exports to Excel and various Excel operation examples. The detailed code is compiled here. Friends in need can refer to it.
First export the code
##
/// <summary> /// 导出速度最快 /// </summary> /// <param name="list"><列名,数据></param> /// <param name="filepath"></param> /// <returns></returns> public bool NewExport(List<DictionaryEntry> list, string filepath) { bool bSuccess = true; Microsoft.Office.Interop.Excel.Application appexcel = new Microsoft.Office.Interop.Excel.Application(); System.Reflection.Missing miss = System.Reflection.Missing.Value; appexcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbookdata = null; Microsoft.Office.Interop.Excel.Worksheet worksheetdata = null; Microsoft.Office.Interop.Excel.Range rangedata; workbookdata = appexcel.Workbooks.Add(); //设置对象不可见 appexcel.Visible = false; appexcel.DisplayAlerts = false; try { foreach (var lv in list) { var keys = lv.Key as List<string>; var values = lv.Value as List<IList<object>>; worksheetdata = (Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets.Add(miss, workbookdata.ActiveSheet); for (int i = 0; i < keys.Count-1; i++) { //给工作表赋名称 worksheetdata.Name = keys[0];//列名的第一个数据位表名 worksheetdata.Cells[1, i + 1] = keys[i+1]; } //因为第一行已经写了表头,所以所有数据都应该从a2开始 rangedata = worksheetdata.get_Range("a2", miss); Microsoft.Office.Interop.Excel.Range xlrang = null; //irowcount为实际行数,最大行 int irowcount = values.Count; int iparstedrow = 0, icurrsize = 0; //ieachsize为每次写行的数值,可以自己设置 int ieachsize = 10000; //icolumnaccount为实际列数,最大列数 int icolumnaccount = keys.Count-1; //在内存中声明一个ieachsize×icolumnaccount的数组,ieachsize是每次最大存储的行数,icolumnaccount就是存储的实际列数 object[,] objval = new object[ieachsize, icolumnaccount]; icurrsize = ieachsize; while (iparstedrow < irowcount) { if ((irowcount - iparstedrow) < ieachsize) icurrsize = irowcount - iparstedrow; //用for循环给数组赋值 for (int i = 0; i < icurrsize; i++) { for (int j = 0; j < icolumnaccount; j++) { var v = values[i + iparstedrow][j]; objval[i, j] = v != null ? v.ToString() : ""; } } string X = "A" + ((int)(iparstedrow + 2)).ToString(); string col = ""; if (icolumnaccount <= 26) { col = ((char)('A' + icolumnaccount - 1)).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString(); } else { col = ((char)('A' + (icolumnaccount / 26 - 1))).ToString() + ((char)('A' + (icolumnaccount % 26 - 1))). ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString(); } xlrang = worksheetdata.get_Range(X, col); xlrang.NumberFormat = "@"; // 调用range的value2属性,把内存中的值赋给excel xlrang.Value2 = objval; iparstedrow = iparstedrow + icurrsize; } } ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet1"]).Delete(); ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet2"]).Delete(); ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet3"]).Delete(); //保存工作表 workbookdata.SaveAs(filepath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); workbookdata.Close(false, miss, miss); appexcel.Workbooks.Close(); appexcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbookdata); System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel.Workbooks); System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel); GC.Collect(); } catch (Exception ex) { ErrorMsg = ex.Message; bSuccess = false; } finally { if (appexcel != null) { ExcelImportHelper.KillSpecialExcel(appexcel); } } return bSuccess; }
range.NumberFormatLocal = "@"; //设置单元格格式为文本 range = (Range)worksheet.get_Range("A1", "E1"); //获取Excel多个单元格区域:本例做为Excel表头 range.Merge(0); //单元格合并动作 worksheet.Cells[1, 1] = "Excel单元格赋值"; //Excel单元格赋值 range.Font.Size = 15; //设置字体大小 range.Font.Underline=true; //设置字体是否有下划线 range.Font.Name="黑体"; 设置字体的种类 range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //设置字体在单元格内的对其方式 range.ColumnWidth=15; //设置单元格的宽度 range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb(); //设置单元格的背景色 range.Borders.LineStyle=1; //设置单元格边框的粗细 range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb()); //给单元格加边框 range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //设置单元格上边框为无边框 range.EntireColumn.AutoFit(); //自动调整列宽 Range.HorizontalAlignment= xlCenter; // 文本水平居中方式 Range.VerticalAlignment= xlCenter //文本垂直居中方式 Range.WrapText=true; //文本自动换行 Range.Interior.ColorIndex=39; //填充颜色为淡紫色 Range.Font.Color=clBlue; //字体颜色 xlsApp.DisplayAlerts=false; //对Excel的操作 不弹出提示信息 ApplicationClass xlsApp = new ApplicationClass(); // 1. 创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。 if (xlsApp == null) { //对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel }
Workbook workbook = xlsApp.Workbooks.Open(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Worksheet mySheet = workbook.Sheets[1] as Worksheet; //第一个sheet页 mySheet.Name = "testsheet"; //这里修改sheet名称
mySheet.Copy(Type.Missing, workbook.Sheets[1]); //复制mySheet成一个新的sheet页,复制完后的名称是mySheet页名称后加一个(2),这里就是testsheet(2),复制完后,Worksheet的数量增加一个
xlsApp.DisplayAlerts = false; //如果想删除某个sheet页,首先要将此项设为fasle。 (xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete();
Copy code The code is as follows:
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select( Type.Missing); //Select a sheet
workbook.Saved = true; workbook.SaveCopyAs(filepath);
##
workbook.Close(true, Type.Missing, Type.Missing); workbook = null; xlsApp.Quit(); xlsApp = null;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; using System.Data; namespace ExcelTest { public class ExcelUtil { System.Data.DataTable table11 = new System.Data.DataTable(); public void ExportToExcel(System.Data.DataTable table, string saveFileName) { bool fileSaved = false; //ExcelApp xlApp = new ExcelApp(); Application xlApp = new Application(); if (xlApp == null) { return; } Workbooks workbooks = xlApp.Workbooks; Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet); Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1 long rows = table.Rows.Count; /*下边注释的两行代码当数据行数超过行时,出现异常:异常来自HRESULT:0x800A03EC。因为:Excel 2003每个sheet只支持最大行数据 //Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count+2, gridview.Columns.View.VisibleColumns.Count+1]); //fchR.Value2 = datas;*/ if (rows > 65535) { long pageRows = 60000;//定义每页显示的行数,行数必须小于 int scount = (int)(rows / pageRows); if (scount * pageRows < table.Rows.Count)//当总行数不被pageRows整除时,经过四舍五入可能页数不准 { scount = scount + 1; } for (int sc = 1; sc <= scount; sc++) { if (sc > 1) { object missing = System.Reflection.Missing.Value; worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add( missing, missing, missing, missing);//添加一个sheet } else { worksheet = (Worksheet)workbook.Worksheets[sc];//取得sheet1 } string[,] datas = new string[pageRows + 1, table.Columns.Count+ 1]; for (int i = 0; i < table.Columns.Count; i++) //写入字段 { datas[0, i] = table.Columns[i].Caption; } Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]); range.Interior.ColorIndex = 15;//15代表灰色 range.Font.Bold = true; range.Font.Size = 9; int init = int.Parse(((sc - 1) * pageRows).ToString()); int r = 0; int index = 0; int result; if (pageRows * sc >= table.Rows.Count) { result = table.Rows.Count; } else { result = int.Parse((pageRows * sc).ToString()); } for (r = init; r < result; r++) { index = index + 1; for (int i = 0; i < table.Columns.Count; i++) { if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal) || table.Columns[i].DataType == typeof(DateTime)) { object obj = table.Rows[r][table.Columns[i].ColumnName]; datas[index, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式 } } } Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[index + 2, table.Columns.Count + 1]); fchR.Value2 = datas; worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。 range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[index + 1, table.Columns.Count]); //15代表灰色 range.Font.Size = 9; range.RowHeight = 14.25; range.Borders.LineStyle = 1; range.HorizontalAlignment = 1; } } else { string[,] datas = new string[table.Rows.Count + 2, table.Columns.Count + 1]; for (int i = 0; i < table.Columns.Count; i++) //写入字段 { datas[0, i] = table.Columns[i].Caption; } Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]); range.Interior.ColorIndex = 15;//15代表灰色 range.Font.Bold = true; range.Font.Size = 9; int r = 0; for (r = 0; r < table.Rows.Count; r++) { for (int i = 0; i < table.Columns.Count; i++) { if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal) || table.Columns[i].DataType == typeof(DateTime)) { object obj = table.Rows[r][table.Columns[i].ColumnName]; datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式 } } //System.Windows.Forms.Application.DoEvents(); } Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 1]); fchR.Value2 = datas; worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。 range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1, table.Columns.Count]); //15代表灰色 range.Font.Size = 9; range.RowHeight = 14.25; range.Borders.LineStyle = 1; range.HorizontalAlignment = 1; } if (saveFileName != "") { try { workbook.Saved = true; workbook.SaveCopyAs(saveFileName); fileSaved = true; } catch (Exception ex) { fileSaved = false; } } else { fileSaved = false; } xlApp.Quit(); GC.Collect();//强行销毁 } } }
##Method 3:
Go first Official website: http://www.php.cn/ To download, you need to introduce the dll (you can choose .net2.0 or .net4.0 dll), and then add a reference to the website. Export code:
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("test_01"); // 第一列 NPOI.SS.UserModel.IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue("第一列第一行"); // 第二列 NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(1); row2.CreateCell(0).SetCellValue("第二列第一行"); // ... // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); Response.BinaryWrite(ms.ToArray()); book = null; ms.Close(); ms.Dispose();
##
HSSFWorkbook hssfworkbook; #region public DataTable ImportExcelFile(string filePath) { #region//初始化信息 try { using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { hssfworkbook = new HSSFWorkbook(file); } } catch (Exception e) { throw e; } #endregion NPOI.SS.UserModel.Sheet sheet = hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); DataTable dt = new DataTable(); for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++) { dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString()); } while (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; DataRow dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { NPOI.SS.UserModel.Cell cell = row.GetCell(i); if (cell == null) { dr[i] = null; } else { dr[i] = cell.ToString(); } } dt.Rows.Add(dr); } return dt; } #endregion
Usage:
First create a blank workbook for testing, create a blank worksheet in it, and create a blank in the table Row, create a cell in the row and fill in the content:
//建立空白工作簿 IWorkbook workbook = new HSSFWorkbook(); //在工作簿中:建立空白工作表 ISheet sheet = workbook.CreateSheet(); //在工作表中:建立行,参数为行号,从0计 IRow row = sheet.CreateRow(0); //在行中:建立单元格,参数为列号,从0计 ICell cell = row.CreateCell(0); //设置单元格内容 cell.SetCellValue("实习鉴定表");
Set cell style: Required when setting cell style Note that you must create a new style object for setting, otherwise the styles of all cells in the worksheet will be set together. They should share a style object:
ICellStyle style = workbook.CreateCellStyle(); //设置单元格的样式:水平对齐居中 style.Alignment = HorizontalAlignment.CENTER; //新建一个字体样式对象 IFont font = workbook.CreateFont(); //设置字体加粗样式 font.Boldweight = short.MaxValue; //使用SetFont方法将字体样式添加到单元格样式中 style.SetFont(font); //将新的样式赋给单元格 cell.CellStyle = style;
Setting the width of the cell actually sets the width of the column where it is located, so To set it on the column where the cell is located (the column setting is on the worksheet), the width value seems to be 1/256 of the character, so *256 is used to achieve the setting effect.
//设置单元格的高度 row.Height = 30 * 20; //设置单元格的宽度 sheet.SetColumnWidth(0, 30 * 256);
Merge cells actually declare a range and the cells in the range The cells will be merged, and the merged content and style will be based on the cell in the upper left corner of the area.
//设置一个合并单元格区域,使用上下左右定义CellRangeAddress区域
//CellRangeAddress四个参数为:起始行,结束行,起始列,结束列
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 10));
Use Cell's CellFormula to set the formula. It is a string. There is no prefix before the formula. Need to add = sign.
//通过Cell的CellFormula向单元格中写入公式
//注:直接写公式内容即可,不需要在最前加'='
ICell cell2 = sheet.CreateRow(1).CreateCell(0);
cell2.CellFormula = "HYPERLINK(\"测试图片.jpg\",\"测试图片.jpg\")";
//将工作簿写入文件
using (FileStream fs = new FileStream("生成效果.xls", FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
The above is the detailed explanation of the example code of C# to export hundreds of thousands of data to Excel and various Excel operations. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!

如何使用C#编写时间序列预测算法时间序列预测是一种通过分析过去的数据来预测未来数据趋势的方法。它在很多领域,如金融、销售和天气预报中有广泛的应用。在本文中,我们将介绍如何使用C#编写时间序列预测算法,并附上具体的代码示例。数据准备在进行时间序列预测之前,首先需要准备好数据。一般来说,时间序列数据应该具有足够的长度,并且是按照时间顺序排列的。你可以从数据库或者

如何使用Redis和C#开发分布式事务功能引言分布式系统的开发中,事务处理是一项非常重要的功能。事务处理能够保证在分布式系统中的一系列操作要么全部成功,要么全部回滚。Redis是一种高性能的键值存储数据库,而C#是一种广泛应用于开发分布式系统的编程语言。本文将介绍如何使用Redis和C#来实现分布式事务功能,并提供具体代码示例。I.Redis事务Redis

如何实现C#中的人脸识别算法人脸识别算法是计算机视觉领域中的一个重要研究方向,它可以用于识别和验证人脸,广泛应用于安全监控、人脸支付、人脸解锁等领域。在本文中,我们将介绍如何使用C#来实现人脸识别算法,并提供具体的代码示例。实现人脸识别算法的第一步是获取图像数据。在C#中,我们可以使用EmguCV库(OpenCV的C#封装)来处理图像。首先,我们需要在项目

Redis在C#开发中的应用:如何实现高效的缓存更新引言:在Web开发中,缓存是提高系统性能的常用手段之一。而Redis作为一款高性能的Key-Value存储系统,能够提供快速的缓存操作,为我们的应用带来了不少便利。本文将介绍如何在C#开发中使用Redis,实现高效的缓存更新。Redis的安装与配置在开始之前,我们需要先安装Redis并进行相应的配置。你可以

如何使用C#编写动态规划算法摘要:动态规划是求解最优化问题的一种常用算法,适用于多种场景。本文将介绍如何使用C#编写动态规划算法,并提供具体的代码示例。一、什么是动态规划算法动态规划(DynamicProgramming,简称DP)是一种用来求解具有重叠子问题和最优子结构性质的问题的算法思想。动态规划将问题分解成若干个子问题来求解,通过记录每个子问题的解,

如何实现C#中的图像压缩算法摘要:图像压缩是图像处理领域中的一个重要研究方向,本文将介绍在C#中实现图像压缩的算法,并给出相应的代码示例。引言:随着数字图像的广泛应用,图像压缩成为了图像处理中的重要环节。压缩能够减小存储空间和传输带宽,并能提高图像处理的效率。在C#语言中,我们可以通过使用各种图像压缩算法来实现对图像的压缩。本文将介绍两种常见的图像压缩算法:

C#开发中如何处理跨域请求和安全性问题在现代的网络应用开发中,跨域请求和安全性问题是开发人员经常面临的挑战。为了提供更好的用户体验和功能,应用程序经常需要与其他域或服务器进行交互。然而,浏览器的同源策略导致了这些跨域请求被阻止,因此需要采取一些措施来处理跨域请求。同时,为了保证数据的安全性,开发人员还需要考虑一些安全性问题。本文将探讨C#开发中如何处理跨域请

如何在C#中实现遗传算法引言:遗传算法是一种模拟自然选择和基因遗传机制的优化算法,其主要思想是通过模拟生物进化的过程来搜索最优解。在计算机科学领域,遗传算法被广泛应用于优化问题的解决,例如机器学习、参数优化、组合优化等。本文将介绍如何在C#中实现遗传算法,并提供具体的代码示例。一、遗传算法的基本原理遗传算法通过使用编码表示解空间中的候选解,并利用选择、交叉和


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
