生成EXCEL文件是经常需要用到的功能,我们利用一些开源库可以很容易实现这个功能。

方法一:利用excellibraryhttp://code.google.com/p/excellibrary/

excellibrary是国人写的开源组件,很容易使用,可惜貌似还不支持.xlsx(Excel 2007),例子如下:

//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();
//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
//Add the table to the data set
ds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

  

例子二:

//create new xls file
string file = "C:\\newdoc.xls";
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("First Sheet");
worksheet.Cells[, ] = new Cell((short));
worksheet.Cells[, ] = new Cell();
worksheet.Cells[, ] = new Cell((decimal)3.45);
worksheet.Cells[, ] = new Cell("Text string");
worksheet.Cells[, ] = new Cell("Second string");
worksheet.Cells[, ] = new Cell(32764.5, "#,##0.00");
worksheet.Cells[, ] = new Cell(DateTime.Now, @"YYYY\-MM\-DD");
worksheet.Cells.ColumnWidth[, ] = ;
workbook.Worksheets.Add(worksheet);
workbook.Save(file);
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[];
// traverse cells
foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
{
dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
}
// traverse rows by Index
for (int rowIndex = sheet.Cells.FirstRowIndex;
rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex;
colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
}
}

方法二:利用EPPlus,http://epplus.codeplex.com/
EPPlus是一个使用Open Office XML(xlsx)文件格式,能读写Excel 2007/2010 文件的开源组件。
例子如下:

var file = @"Sample.xlsx";
if (File.Exists(file)) File.Delete(file);
using (var excel = new ExcelPackage(new FileInfo(file)))
{
var ws = excel.Workbook.Worksheets.Add("Sheet1");
ws.Cells[1, 1].Value = "Date";
ws.Cells[1, 2].Value = "Price";
ws.Cells[1, 3].Value = "Volume";
var random = new Random();
for (int i = 0; i < 10; i++)
{
ws.Cells[i + 2, 1].Value = DateTime.Today.AddDays(i);
ws.Cells[i + 2, 2].Value = random.NextDouble() * 1e3;
ws.Cells[i + 2, 3].Value = random.Next() / 1e3;
} ws.Cells[2, 1, 11, 1].Style.Numberformat.Format = "dd/MM/yyyy";
ws.Cells[2, 2, 11, 2].Style.Numberformat.Format = "#,##0.000000";
ws.Cells[2, 3, 11, 3].Style.Numberformat.Format = "#,##0";
ws.Column(1).AutoFit();
ws.Column(2).AutoFit();
ws.Column(3).AutoFit();
excel.Save();
}

  

例子二:

using OfficeOpenXml;
//指定Templete文档Text.xlsx
FileInfo newFile = new FileInfo("D:" + @"\Test.xlsx");
//开启
using (ExcelPackage pck = new ExcelPackage(newFile))
{
try
{
//设定ExcelWorkBook
ExcelWorkbook workBook = pck.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
//复制Temp这个Sheet同时命名为《清单》
ExcelWorksheet currentWorksheet = workBook.Worksheets.Copy("Temp", "清单");
//可以设定保护Sheet的密码
//currentWorksheet.Protection.SetPassword("1234");
int StartRow = 4;
for (int i = 0; i < tDS.Tables[0].Rows.Count; i++)
{
//Cells[RowIndex,CellIndex]
currentWorksheet.Cells[StartRow + i, 1].Value = Convert.ToString(tDS.Tables[0].Rows[i][0]);
currentWorksheet.Cells[StartRow + i, 2].Value = Convert.ToString(tDS.Tables[0].Rows[i][1]);
currentWorksheet.Cells[StartRow + i, 3].Value = Convert.ToString(tDS.Tables[0].Rows[i][2]);
currentWorksheet.Cells[StartRow + i, 4].Value = Convert.ToString(tDS.Tables[0].Rows[i][3]);
currentWorksheet.Cells[StartRow + i, 5].Value = Convert.ToString(tDS.Tables[0].Rows[i][4]);
currentWorksheet.Cells[StartRow + i, 6].Value = Convert.ToString(tDS.Tables[0].Rows[i][5]);
currentWorksheet.Cells[StartRow + i, 7].Value = Convert.ToString(tDS.Tables[0].Rows[i][6]);
currentWorksheet.Cells[StartRow + i, 8].Value = Convert.ToString(tDS.Tables[0].Rows[i][7]);
currentWorksheet.Cells[StartRow + i, 9].Value = Convert.ToString(tDS.Tables[0].Rows[i][8]);
currentWorksheet.Cells[StartRow + i, 10].Value = Convert.ToString(tDS.Tables[0].Rows[i][9]);
currentWorksheet.Cells[StartRow + i, 11].Value = Convert.ToString(tDS.Tables[0].Rows[i][10]);
currentWorksheet.Cells[StartRow + i, 12].Value = Convert.ToString(tDS.Tables[0].Rows[i][11]);
currentWorksheet.Cells[StartRow + i, 13].Value = Convert.ToString(tDS.Tables[0].Rows[i][12]);
}
//将Temp 这个Sheet删除
workBook.Worksheets.Delete("Temp");
}
}
//存至Text4.xlsx
pck.SaveAs(new FileInfo("H:" + @"\Test4.xlsx"));
}
catch (Exception e)
{
oLogger.Fatal(e.ToString());
}
}

  

方法三:NPOI http://npoi.codeplex.com/
NPOI无需Office COM组件且不依赖Office,使用NPOI能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。
被人称为操作EXCEL的终极方案,例子如下:

//引用
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
//将WorkBook指到我们原本设计好的Templete Book1.xls
using (IWorkbook wb = new HSSFWorkbook(new FileStream("D:/Book1.xls", FileMode.Open)))
{
try
{
//设定要使用的Sheet为第0个Sheet
ISheet TempSheet = wb.GetSheetAt(0);
int StartRow = 4;
//tDS为Query回来的资料
for (int i = 0; i < tDS.Tables[0].Rows.Count; i++)
{
//第一个Row要用Create的
TempSheet.CreateRow(StartRow + i).CreateCell(0).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][0]));
//第二个Row之后直接用Get的
TempSheet.GetRow(StartRow + i).CreateCell(1).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][1]));
TempSheet.GetRow(StartRow + i).CreateCell(2).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][2]));
TempSheet.GetRow(StartRow + i).CreateCell(3).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][3]));
TempSheet.GetRow(StartRow + i).CreateCell(4).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][4]));
TempSheet.GetRow(StartRow + i).CreateCell(5).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][5]));
TempSheet.GetRow(StartRow + i).CreateCell(6).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][6]));
TempSheet.GetRow(StartRow + i).CreateCell(7).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][7]));
TempSheet.GetRow(StartRow + i).CreateCell(8).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][8]));
TempSheet.GetRow(StartRow + i).CreateCell(9).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][9]));
TempSheet.GetRow(StartRow + i).CreateCell(10).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][10]));
TempSheet.GetRow(StartRow + i).CreateCell(11).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][11]));
TempSheet.GetRow(StartRow + i).CreateCell(12).SetCellValue(Convert.ToString(tDS.Tables[0].Rows[i][12]));
}
//将文档写到指定位置
using (FileStream file = new FileStream("H:/Test_NPOI4.xls", FileMode.Create))
{
wb.Write(file);
file.Close();
file.Dispose();
}
}
catch (Exception e)
{
string a = e.ToString();
}
}

  

C#创建Excel(.xls和.xlsx)文件的三种方法的更多相关文章

  1. 如何使用Java创建Excel(.xls 和 .xlsx)文件 并写入数据

    1,需要依赖的jar包, <!-- POI(operate excel) start --> <!-- the version of the following POI packag ...

  2. C# 操作 Excel(.xls和.xlsx)文件

    C#创建Excel(.xls和.xlsx)文件的三种方法 .NET 使用NPOI导入导出标准Excel C# 使用NPOI 实现Excel的简单导入导出 NET使用NPOI组件将数据导出Excel-通 ...

  3. python pandas合并多个excel(xls和xlsx)文件(弹窗选择文件夹和保存文件)

    # python pandas合并多个excel(xls和xlsx)文件(弹窗选择文件夹和保存文件) import tkinter as tk from tkinter import filedial ...

  4. VC中加载LIB库文件的三种方法

    VC中加载LIB库文件的三种方法 在VC中加载LIB文件的三种方法如下: 方法1:LIB文件直接加入到工程文件列表中   在VC中打开File View一页,选中工程名,单击鼠标右键,然后选中&quo ...

  5. php将数组写入到文件的三种方法

    php将数组原样写入或保存到文件有三种方法可以实现, 第一种方法是使用serialize, 第二种方法是使用print_r, 第三种方法是使用var_export, 本文章向大家介绍这三种方法是如何将 ...

  6. Node.js写文件的三种方法

    Node.js写文件的三种方式: 1.通过管道流写文件 采用管道传输二进制流,可以实现自动管理流,可写流不必当心可读流流的过快而崩溃,适合大小文件传输(推荐) var readStream = fs. ...

  7. Logstash处理json格式日志文件的三种方法

    假设日志文件中的每一行记录格式为json的,如: {"Method":"JSAPI.JSTicket","Message":"JS ...

  8. Python实现下载文件的三种方法

    下面来看看三种方法是如何来下载zip文件的:方法一: import urllib print "downloading with urllib" url = 'http://www ...

  9. Viewing the interface of your Swift code,查看Swift代码的头文件的三种方法

      Technical Q&A QA1914 Viewing the interface of your Swift code Q:  How do I view the interface ...

随机推荐

  1. c#编程基础之函数可变参数

    可变参数:int sum (params int[] values)int sum (string name,params int[] values) 注意:params参数必须是形参表中的最后一个参 ...

  2. docker对数据卷进行还原操作

    转载请注明出处 数据卷容器备份数据后,备份数据查看 http://www.cnblogs.com/zhuxiaojie/p/5947138.html   我们可能要把这个备份的数据,还原到另一台的do ...

  3. WCF学习系列汇总

    最近在学习WCF,打算把一整个系列的文章都”写“出来,包括理论和实践,这里的“写”是翻译,是国外的大牛写好的,我只是搬运工外加翻译.翻译的不好,大家请指正,谢谢了.如果觉得不错的话,也可以给我点赞,这 ...

  4. Visual Studio (VSIX,项目模板 )制作

    下载Vsiual Studio 2012 SDK 下载地址:http://www.microsoft.com/en-us/download/details.aspx?id=30668 提示:一定要注意 ...

  5. [翻译+山寨]Hangfire Highlighter Tutorial

    前言 Hangfire是一个开源且商业免费使用的工具函数库.可以让你非常容易地在ASP.NET应用(也可以不在ASP.NET应用)中执行多种类型的后台任务,而无需自行定制开发和管理基于Windows ...

  6. Java终止线程

    Thread提供了stop()方法终止线程,但是该方法是强行终止,容易产生一些错误,已经被废弃. 可以使用退出标志来终止线程,在run()函数里面设置while循环,把退出标志作为while的条件,当 ...

  7. [示例] Firemonkey OnTouch 多点触控应用

    说明:Firemonkey OnTouch 多点触控应用,可同时多指移动多个不同控件 原码下载:[原创]TestMultitouchMove_多点触控应用_by_Aone.zip 运行展示:

  8. expect基本使用方法

    参考: http://www.cnblogs.com/lzrabbit/p/4298794.html expect是linux系统中可以和子进程进行交互的一个命令,使用它可以做一些自动化工作.pyth ...

  9. pandas.DataFrame排除特定行

    使用Python进行数据分析时,经常要使用到的一个数据结构就是pandas的DataFrame 如果我们想要像Excel的筛选那样,只要其中的一行或某几行,可以使用isin()方法,将需要的行的值以列 ...

  10. JavaScript--面向对象--猜拳游戏

    //html代码 <!doctype html> <html> <head> <meta charset="UTF-8"> < ...