csharp: read excel using Aspose.Cells
/// <summary>
///
/// </summary>
/// <param name="strFileName"></param>
/// <returns></returns>
public static System.Data.DataTable ReadExcel(String strFileName)
{
Workbook book = new Workbook(strFileName);
//book.Open(strFileName); //老版本
Worksheet sheet = book.Worksheets[0]; Cells cells = sheet.Cells; return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
}
/// <summary>
///
/// </summary>
/// <param name="strFileName"></param>
/// <param name="sheetname"></param>
/// <returns></returns>
public static System.Data.DataTable ReadExcel(String strFileName,string sheetname)
{
Workbook book = new Workbook(strFileName);
//book.Open(strFileName);//老版本
Worksheet sheet = book.Worksheets[sheetname]; Cells cells = sheet.Cells; return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
}
/// <summary>
/// 读取工作表
/// 涂聚文
/// 20150228
/// </summary>
/// <param name="strFileName"></param>
/// <param name="comb"></param>
public static void ReadExcelCombox(String strFileName, System.Windows.Forms.ComboBox comb)
{
comb.Items.Clear();
Workbook book = new Workbook(strFileName);
// book.Open(strFileName);//老版本
Worksheet sheet = book.Worksheets[0];
for (int i = 0; i < book.Worksheets.Count; i++)
{
comb.Items.Add(book.Worksheets[i].Name.ToString());
}
// Cells cells = sheet.Cells; //return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
} /// <summary>
/// DataTable导出到EXCEL
/// http://www.aspose.com/docs/display/cellsnet/Aspose.Cells+Object+Model
/// http://www.aspose.com/docs/display/cellsnet/Converting+Worksheet+to+Image+and+Worksheet+to+Image+by+Page
/// </summary>
/// <param name="datatable"></param>
/// <param name="filepath"></param>
/// <param name="error"></param>
/// <returns></returns>
public static bool DataTableToExcel(DataTable datatable, string filepath, out string error)
{
error = "";
try
{
if (datatable == null)
{
error = "DataTableToExcel:datatable 为空";
return false;
} Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
Aspose.Cells.Worksheet sheet = workbook.Worksheets[0];
Aspose.Cells.Cells cells = sheet.Cells; int nRow = 0;
foreach (DataRow row in datatable.Rows)
{
nRow++;
try
{
for (int i = 0; i < datatable.Columns.Count; i++)
{
if (row[i].GetType().ToString() == "System.Drawing.Bitmap")
{
//------插入图片数据-------
System.Drawing.Image image = (System.Drawing.Image)row[i];
MemoryStream mstream = new MemoryStream();
image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
sheet.Pictures.Add(nRow, i, mstream);
}
else
{
cells[nRow, i].PutValue(row[i]);
}
}
}
catch (System.Exception e)
{
error = error + " DataTableToExcel: " + e.Message;
}
} workbook.Save(filepath);
return true;
}
catch (System.Exception e)
{
error = error + " DataTableToExcel: " + e.Message;
return false;
}
}
/// <summary>
/// 工作表转为图片
/// </summary>
/// <param name="file">来源EXCEL文件</param>
/// <param name="sheetname">工作表名</param>
/// <param name="toimagefile">生成图片文件</param>
public static void CellConverImge(string file, string sheetname, string toimagefile)
{
//Create a new Workbook object and
//Open a template Excel file.
Workbook book = new Workbook(file);
//Get the first worksheet.
Worksheet sheet = book.Worksheets[sheetname]; //Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
//Specify the image format
imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
//Only one page for the whole sheet would be rendered
imgOptions.OnePagePerSheet = true; //Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, imgOptions);
//Render the image for the sheet
Bitmap bitmap = sr.ToImage(0); //Save the image file specifying its image format.
bitmap.Save(toimagefile);
} /// <summary>
///
/// </summary>
/// <param name="sURL"></param>
/// <param name="toExcelFile"></param>
public static void LoadUrlImage(string sURL,string toExcelFile)
{
//Define memory stream object
System.IO.MemoryStream objImage; //Define web client object
System.Net.WebClient objwebClient; //Define a string which will hold the web image url
//string sURL = "http://files.myopera.com/Mickeyjoe_irl/albums/38458/abc.jpg"; try
{
//Instantiate the web client object
objwebClient = new System.Net.WebClient(); //Now, extract data into memory stream downloading the image data into the array of bytes
objImage = new System.IO.MemoryStream(objwebClient.DownloadData(sURL)); //Create a new workbook
Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(); //Get the first worksheet in the book
Aspose.Cells.Worksheet sheet = wb.Worksheets[0]; //Get the first worksheet pictures collection
Aspose.Cells.Drawing.PictureCollection pictures = sheet.Pictures; //Insert the picture from the stream to B2 cell
pictures.Add(1, 1, objImage); //Save the excel file "d:\\test\\webimagebook.xls"
wb.Save(toExcelFile);
}
catch (Exception ex)
{
//Write the error message on the console
Console.WriteLine(ex.Message);
}
}
/// <summa /// <summary>
/// 涂聚文
/// 20150228
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFile_Click(object sender, EventArgs e)
{
try
{
//bool imail = false;
this.Cursor = Cursors.WaitCursor;
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Excel 2000-2003 files(*.xls)|*.xls|Excel 2007 files (*.xlsx)|*.xlsx";//|(*.xlsx)|*.xlsx Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.* txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!openFileDialog1.FileName.Equals(String.Empty))
{
//重新加载清除数据
this.combSheet.DataSource = null;
if (this.combSheet.Items.Count != 0)
{
this.combSheet.Items.Clear();
}
FileInfo f = new FileInfo(openFileDialog1.FileName);
if (f.Extension.Equals(".xls") || f.Extension.Equals(".XLS") || f.Extension.Equals(".xlsx"))
{
this.Cursor = Cursors.WaitCursor;
strFileUrl = openFileDialog1.SafeFileName;
this.txtFileUrl.Text = openFileDialog1.FileName;
string currentfilename = openFileDialog1.FileName;
this.txtFileUrl.Text = currentfilename; //
// ("463588883@qq.com", "geovindu", "金至尊文件", "文件", currentfilename);
//MessageBox.Show(imail.ToString());
AsposeExcel.ReadExcelCombox(currentfilename,combSheet); this.Cursor = Cursors.Default;
}
else
{
MessageBox.Show("错添文件类型");
}
}
else
{
MessageBox.Show("你要选择一下精确位置的文件");
} }
}
catch (Exception ex)
{
ex.Message.ToString();
}
this.Cursor = Cursors.Default;
}
/// <summary>
/// 导入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnImport_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//默认第一行为标题
dt= AsposeExcel.ReadExcel(this.txtFileUrl.Text.Trim(), this.combSheet.Text.Trim()); this.dataGridView1.DataSource = dt; }
/// <summary>
///
/// </summary>
public partial class _Default : System.Web.UI.Page
{ DataTable getData()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
dt.Rows.Add(1, "geovindu");
dt.Rows.Add(2, "geov");
return dt;
} /// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GridView1.DataSource = getData();
this.GridView1.DataBind(); }
}
/// <summary>
///
/// </summary>
/// <param name="dataTable"></param>
/// <param name="fileName"></param>
protected void ExportToExcel(DataTable dataTable, string fileName)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in dataTable.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine); foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
context.Response.Write(row[i].ToString() + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "application / ms - excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
context.Response.End();
} protected void Button1_Click(object sender, EventArgs e)
{
ExportToExcel(getData(), "toni");
}
csharp: read excel using Aspose.Cells的更多相关文章
- ASPOSE.Cells & ASPOSE.Words 操纵Excel和Word文档的 .NET Core 实例
Aspose.Total是Aspose公司旗下的最全的一套office文档管理方案,它提供的原生API可以对Word.Excel.PDF.Powerpoint.Outlook.CAD.图片.3D.ZI ...
- C# WinForm 导出导入Excel/Doc 完整实例教程[使用Aspose.Cells.dll]
[csharp] view plain copy 1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 ...
- C#使用Aspose.Cells导出Excel简单实现
首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...
- Aspose.Cells导出Excel(2)
DataTable dtTitle = ds.Tables[]; DataTable dtDetail = ds.Tables[]; int columns = dtTitle.Columns.Cou ...
- Aspose.Cells导出Excel(1)
利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ...
- 使用Aspose.Cells读取Excel
最新更新请访问: http://denghejun.github.io Aspose.Cells读取Excel非常方便,以下是一个简单的实现读取和导出Excel的操作类: 以下是Aspose.Ce ...
- NPOI、MyXls、Aspose.Cells 导入导出Excel(转)
Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导s出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你 ...
- Asp.Net中应用Aspose.Cells输出报表到Excel 及样式设置
解决思路: 1.找个可用的Aspose.Cells(有钱还是买个正版吧,谁开发个东西也不容易): 2.在.Net方案中引用此Cells: 3.写个函数ToExcel(传递一个DataTable),可以 ...
- java利用Aspose.cells.jar将本地excel文档转化成pdf(完美破解版 无水印 无中文乱码)
下载aspose-cells-8.5.2.jar包 http://pan.baidu.com/s/1kUBzsQ7 JAVA代码 package webViewer; import java.io.* ...
随机推荐
- [CISCO] 简单配置 Telnet 服务
[CISCO] 简单配置 Telnet 服务 一.Introduction Telnet 协议是一种应用层协议,使用于网际网路及区域网中,使用虚拟终端机的形式,提供双向.以文字字串为主的互动功能.属于 ...
- Myeclipse设置自动联想功能
///声明,博客园暂无转载功能,这篇博客是转载自贞心真义. 最近初学Java,正在使用MyEclipse来编写新的项目,刚开始打开MyEclipse感觉这个工具既陌生又熟悉,熟悉之处在于编辑器的几大共 ...
- python 爬恶魔法则(单线程卡成狗)
from bs4 import BeautifulSoupimport requestsimport sysclass down(object): def __init__(self): self.n ...
- 类型转换:static_cast、reinterpret_cast等
一.隐式类型转换 系统自动进行,不需要程序开发人员介入. int m = 3 + 45.6;// 48 把小数部分截掉,也属于隐式类型转换的一部分 double b = 3 + 45.6; // 48 ...
- finally语句块一定会执行吗?
public class SystemExitAndFinally { public static void main(String[] args) { try{ System.out.println ...
- 九省联考 2018 Day 1 复现
前言 今年省选还有 15 天.每天针对性刷题学知识点有点枯燥,想到真题还没刷,就对着 pdf 做了一遍. A. 一双木棋 去年省选得了 25,应该是 \(n=2,m=2\) 的贪心和 \(m=1\) ...
- 关于window.onload和body onload冲突的解决办法
在学习用js在 页面中动态显示当前时间 和依次读取公告栏信息的 实验中 发现在将两个页面整合时 window.onload=function (){}和 <body onload="d ...
- FAQ of db2fmp messages in the db2diag.log
http://www-01.ibm.com/support/docview.wss?uid=swg21470035 Technote (FAQ) Question What do these mess ...
- (转)OpenStack构架知识梳理
http://www.cnblogs.com/kevingrace/p/8459034.html-------------------Openstack架构概念图-简单汇总 原文:http://www ...
- hadoop ——HDFS存储
一.HDFS概念 二.HDFS优缺点 三.HDFS如何存储 一.HDFS概念 HDFS(Hadoop Distributed File System)是Hadoop项目的核心子项目,是分布式计算中数据 ...