生成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. OWIN与Katana详解

    前言 我胡汉三又回来了,!!!!, 最近忙成狗,实在没空写博文,实在对不起自己,博客园上逛了逛发现 我大微软还是很给力的 asp.net core 1.0 .net core 1.0 即将发布,虽然. ...

  2. MessageBox.Show()的各种用法

    [函数] <整型> MessageBox(<字符串> Text, <字符串> Title, <整型> nType,MessageBoxIcon); [函 ...

  3. Swing布局管理器介绍

    创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://zhangjunhd.blog.51cto.com/113473/128174 当选 ...

  4. java基础思维导图

    如果图片看不清楚的可以把图片另存为桌面放大看哈

  5. 如何实现一个php框架系列文章【4】url路由管理

    直接通过url参数访问业务模块($app)中控制器($ctl)里的函数($act) 我们支持3种路由模式 普通模式 _a=$app,     _u=$ctl.$act 最简单的方式,专注实现业务$ac ...

  6. Xshell显示中文乱码问题

    [文件]–>[打开]–>在打开的session中选择连接的那个,点击[属性] -> [终端], 编码选择为:Unicode(UTF-8),然后重新连接服务器即可.也可以在Xshell ...

  7. 工作中常用的js、jquery自定义扩展函数代码片段

    仅记录一些我工作中常用的自定义js函数. 1.获取URL请求参数 //根据URL获取Id function GetQueryString(name) { var reg = new RegExp(&q ...

  8. COLLATE匹配两表数据

    MesOrd.MesNO COLLATE Chinese_Taiwan_Stroke_CI_AS = ErpSO.SoNO

  9. Atitit mac os 版本 新特性 attilax大总结

    Atitit mac os 版本 新特性 attilax大总结 1. Macos概述1 2. 早期2 2.1. Macintosh OS (系统 1.0)  1984年2 2.2. Mac OS 7. ...

  10. Java中使用IO流实现大文件的分裂与合并

    文件分割应该算一个比较实用的功能,举例子说明吧比如说:你有一个3G的文件要从一台电脑Copy到另一台电脑, 但是你的存储设备(比如SD卡)只有1G ,这个时候就可以把这个文件切割成3个1G的文件 ,分 ...