Aspose.Cells使用总结大全

使用到 Aspose.Cells 插件,整理一下。

一:新建解决方案,目录如下

  

  目录说明:

    Program.cs - 入口类

    ExcelGenerator.cs - Aspose.Cells 操作类

    Aspose.Cell.dll - 基础dll【文件见文章底部源代码内】

    License.lic - Aspose.Cells 破解证书【文件见文章底部源代码内】

      ps:由于 Aspose.Cells 插件 是收费插件,需要在使用插件前,设置一下许可证,否则在生成的Excel 中 会出现一个名叫 Evaluation Warning 的 Sheet.如图所示:

    


二:Aspose.Cells 操作

  2.1 引入 Aspose.Cell.dll 

  

  2.2 设置 Aspose.Cell.dll 证书 License.lic
    2.2.1 设置证书。我一般都写在生成Excel类的构造函数中了。文件路径要和证书的位置保持一致
Excel.License l = new Excel.License();
l.SetLicense("Aid/License.lic");
    2.2.2 修改证书属性。在解决方案中,右击 License.lic选择属性,修改 Copy to Ouput Directory 属性为 Copy always

    

  2.3 打开现有Execl 模板
复制代码
//模板文件路径
string Template_File_Path = @".\Template\Template.xlsx";

//  打开 Excel 模板
Workbook CurrentWorkbook = File.Exists(Template_File_Path) ? new Workbook(Template_File_Path) : new Workbook();

//  打开第一个sheet
Worksheet DetailSheet = CurrentWorkbook.Worksheets[0];
复制代码
  2.4 写入数据
    2.4.1 填写数据到指定单元格
 // 比如要在 A1 位置写入 Demo这个值

Cell itemCell = DetailSheet.Cells["A1"];

itemCell.PutValue("Demo");
    2.4.2 把DataTable写入到Excel
复制代码
//  获取 Table 数据
DataTable dt = GetData();
            
//  写入数据的起始位置
string cell_start_region = "C1";
//  获得开始位置的行号                    
int startRow = DetailSheet.Cells[cell_start_region].Row;
//  获得开始位置的列号  
int startColumn = DetailSheet.Cells[cell_start_region].Column;  

//  写入Excel。参数说明,直接查阅文章底部文档链接
DetailSheet.Cells.ImportDataTable(dt, false, startRow, startColumn, true, true);
复制代码
  2.5 保存Excel
复制代码
//  设置执行公式计算 - 如果代码中用到公式,需要设置计算公式,导出的报表中,公式才会自动计算
CurrentWorkbook.CalculateFormula(true);

//  生成的文件名称
string ReportFileName = string.Format("Excel_{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd"));

//  保存文件
CurrentWorkbook.Save(@".\Excel\" + ReportFileName, SaveFormat.Xlsx);
 
 
 
/新建工作簿
Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//单元格
 
sheet.Protect(ProtectionType.All, "123123", "");//保护工作表
sheet.Protection.IsSelectingLockedCellsAllowed = false;//设置只能选择解锁单元格
sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
 
Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style1.Font.Name = "宋体";//文字字体
style1.Font.Size = 22;//文字大小
style1.IsLocked = false;//单元格解锁
style1.Font.IsBold = true;//粗体
style1.ForegroundColor = Color.FromArgb(0xaa, 0xcc, 0xbb);//设置背景色
style1.Pattern = BackgroundType.Solid; //设置背景样式
style1.IsTextWrapped = true;//单元格内容自动换行
style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线

style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线

cells.Merge(0, 0, 1, 5);//合并单元格 cells[0, 0].PutValue("内容");//填写内容 cells[0, 0].SetStyle(style1);//给单元格关联样式   cells.SetRowHeight(0, 20);//设置行高 cells.SetColumnWidth(1, 30);//设置列宽 cells[1, 0].Formula = "=AVERAGE(B1:E1)";//给单元格设置计算公式

//从Cells[0,0]开始创建一个2行3列的Range Range range = ws.Cells.CreateRange(0, 0, 2, 3); Cell cell = range[0, 0]; cell.Style.Font = 9; range.Style = style; range.Merge();

注意Range不能直接设置Style.必须先定义style再将style赋给Style.其他设置和Cell基本一致. Range的Style会覆盖Cell定义的Style.另外必须先赋值再传Style.否则可能不生效.

sheet.Cells[0,0].PutValue(1); sheet.Cells[1,0].PutValue(20); sheet.Cells[2,0].Formula="SUM(A1:B1)"; sheet.CalculateFormula(true); Save Excel文件的时候必须调用CalculateFormula方法计算结果.

 

//********************************************************************************

1.创建execl(不需要服务器或者客户端安装office)

public void DCExexl(DataTable dt) {   Workbook wb = new Workbook();   Worksheet ws = wb.Worksheets[0];   Cells cell = ws.Cells;

 

 cell[0, 0].PutValue("ID");//添加数据到第0行和第0列

 cell.SetRowHeight(0, 0);设置行高

 Aspose.Cells.Style style1 = wb.Styles[wb.Styles.Add()];  style1.HorizontalAlignment = TextAlignmentType.Right;//文字居中

 style1.Font.Name = "宋体";  style1.Font.IsBold = true;//设置粗体  style1.Font.Size = 12;//设置字体大小

 cell[0, 0].SetStyle(style1);

 cell.SetColumnWidth(0, 10.00);//列宽

Range range = cell.CreateRange(0, 0, 1, 1);//合并单元格 range.Merge();

 string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";  HttpResponse response = Page.Response;  response.Buffer = true;  response.Charset = "utf-8";  response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);  response.ContentEncoding = System.Text.Encoding.UTF8;  response.ContentType = "application/ms-excel";  response.BinaryWrite(wb.SaveToStream().ToArray());  response.End();

}

2.读取execl

public DataTable GetDataTable(string path) {  Workbook workbook = new Workbook();  workbook.Open(path);  Cells cells = workbook.Worksheets[0].Cells;  DataTable dt = new DataTable();  bool d = true;//防止表头重复加载  for (int i = 0; i < cells.MaxDataRow + 1; i++)  {   DataRow row = dt.NewRow();   for (int j = 0; j < cells.MaxDataColumn + 1; j++)    {     if (d) {      dt.Columns.Add(cells[0, j].StringValue.Trim());     }      row[j] = cells[i + 1, j].StringValue.Trim();  }   dt.Rows.Add(row);   d = false; } return dt; }

 

//*******************************************************************************

读Excel

[csharp] view plain copy print ?
  1.  Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();  
  2.  wk.Open(file);//打开Excel文档  
  3.  Worksheet sht = wk.Worksheets[0];//查看文档的sheet0内容  
  4.  Cells cells = sht.Cells;//获取sheet0的所有单元格  
  5. if (sht==null)  
  6. {  
  7.     return false;  
  8. }  
  9. int rowCount = cells.MaxDataRow+1;//当Excel没有一行数据时,读取到的cells.MaxDataRow=-1,当有一行数据时cells.MaxDataRow=0     MaxDataRow:包含数据的单元格的最大行索引  
  10.   
  11. int cellCount = cells.MaxDataColumn + 1;//当Excel没有一行数据时,读取到的cells.MaxDataRow=-1,当有一行数据时cells.MaxDataRow=0     MaxDataRow:包含数据的单元格的最大列索引  
  12. string title = cells[j, k].Value.ToString();//获取第j行k列单元格的内容  
 Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();
 wk.Open(file);//打开Excel文档
 Worksheet sht = wk.Worksheets[0];//查看文档的sheet0内容
 Cells cells = sht.Cells;//获取sheet0的所有单元格
if (sht==null)
{
    return false;
}
int rowCount = cells.MaxDataRow+1;//当Excel没有一行数据时,读取到的cells.MaxDataRow=-1,当有一行数据时cells.MaxDataRow=0     MaxDataRow:包含数据的单元格的最大行索引

int cellCount = cells.MaxDataColumn + 1;//当Excel没有一行数据时,读取到的cells.MaxDataRow=-1,当有一行数据时cells.MaxDataRow=0     MaxDataRow:包含数据的单元格的最大列索引
string title = cells[j, k].Value.ToString();//获取第j行k列单元格的内容

 

写Excel

[csharp] view plain copy print ?
  1. int _BugNoColumn = cells.MaxDataColumn+1;;//获取最后单元格的内容  
  2. cells.InsertColumn(_BugNoColumn);//在最后单元格的后一列插入一列  
  3. Cell cell = cells[0, _BugNoColumn];//获取插入的那一列的第一行的单元格  
  4. cell.PutValue("abc");//设置单元格的内容为"abc"  

//******************************************************************************************

 

 

上传 

Workbook Workbook workBook = new Workbook(); 

属性: 

 

 名称 值类型  说明 
 Colors  Color[]  获取或设置Excel颜色 
 ConvertNumericData  bool  获取或设置是否将字符串转换至数字数据 
 默认值为 true 
 DataSorter  DataSorter  获取或设置数据分级 
 Date1904  bool  
 DefaultStyle  Aspose.Cells.Style  获取或设置工作簿默认样式 
 HasMacro  bool  获取工作簿是否包含宏观调控或宏 
 IsHScrollBarVisible  bool  获取或设置左部滚动条(控制行) 
  默认值为true 
 IsProtected  bool  获取工作簿保护状态 
 IsVScrollBarVisible  bool  获取或设置底部滚动条(控制列) 
  默认值为true 
  Language   CountryCode --枚举类型  获取或设置语言 
 默认为当前计算机区域 
 Password  string  获取或设置工作簿密码 
 ReCalcOnOpen  bool  获取或设置是否重新计算所有打开文件的公式 
 Region  CountryCode --枚举类型  获取或设置工作簿区域(指当前使用者区域) 
  默认为当前计算机区域 
 Shared  bool  获取或设置当前工作簿是否共享 
 默认为false 
 ShowTabs  bool  获取或设置是否显示标签(工作表标签) 
  默认为true 
 Styles  Styles  样式集合 
 Worksheets  Worksheet  

 

事件: 

 

 CalculateFormula(bool ignoreError 
 ,ICustomFunction customFunction) +3 
 void  计算公式 
 ChangePalette(Color color,int index)  void  设置当前颜色在调色版中显示顺序 
 Combine(Workbook secondWorkbook)  void  联合工作簿,将secondWorkbook 工作簿中workSheet追加到当前工作簿中 
 Copy(Workbook source)  void  拷贝工作簿到当前工作簿 
 Decrypt(string password)  void  解除工作簿密码 
 IsColorInPalette(Color color)  bool  将color加入到当前Excel调色版 
 LoadData(string fileName)   LoadData(System.IO.Stream stream)  void  加载Excel到当前Workbook中 
 Open(string fileName, 
 FileFormatType.Default, 
 string password ); +8 
 void  打开Excel文件 
 Protect(ProtectionType.All, 
 string password); 
 void  写保护,并设置取消工作簿保护密码 
 RemoveExternalLinks()  void  移除外部链接 
 RemoveMacro()  void  移除宏 
 Replace (string PlaceHolder, 
 string newValue); +8 
 void  工作簿中类型和值完全符合的单元格,将其替换为新值或对象 
 Save(Server.UrlEncode("测试.xls"), 
  FileFormatType.Default, 
 SaveType.OpenInExcel, Response);+8 
 Void  保存工作簿 
 SaveToStream()  System.
 
 将工作簿写入内存流中 
 Unprotect(string password);  Void  取消工作簿保护状态 
 ValidateFormula(string formula)  bool  验证公式 

 

-----------

using System;
using System.Collections.Generic;
using System.Text;
using Aspose.Cells;
using System.Data;

namespace CRM.Common
{
    public class AsposeExcel
    {
        private string outFileName = "";
        private Workbook book = null;
        private Worksheet sheet = null;
        private log4net.ILog log = log4net.LogManager.GetLogger(typeof(AsposeExcel));

        public AsposeExcel(string outfilename,string tempfilename)
        {
            outFileName = outfilename;
            book = new Workbook();
            book.Open(tempfilename);
            sheet = book.Worksheets[0];
        }

        private void AddTitle(string title, int columnCount)
        {
            sheet.Cells.Merge(0, 0, 1, columnCount);
            sheet.Cells.Merge(1, 0, 1, columnCount);

            Cell cell1 = sheet.Cells[0, 0];
            cell1.PutValue(title);
            cell1.Style.HorizontalAlignment = TextAlignmentType.Center;
            cell1.Style.Font.Name = "黑体";
            cell1.Style.Font.Size = 14;
            cell1.Style.Font.IsBold = true;

            Cell cell2 = sheet.Cells[1, 0];
            cell1.PutValue("查询时间:" + DateTime.Now.ToLocalTime());
            cell2.SetStyle(cell1.Style);
        }

        private void AddHeader(DataTable dt)
        {
            Cell cell = null;
            for (int col = 0; col < dt.Columns.Count; col++)
            {
                cell = sheet.Cells[0, col];
                cell.PutValue(dt.Columns[col].ColumnName);
                cell.Style.Font.IsBold = true;
            }
        }

        private void AddBody(DataTable dt)
        {
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    sheet.Cells[r + 3, c].PutValue(dt.Rows[r][c].ToString());
                }
            }
        }

        public void DatatableToExcel(DataTable dt)
        {
            try
            {
                //sheet.Name = sheetName;
                
                //AddTitle(title, dt.Columns.Count);
                //AddHeader(dt);
                AddBody(dt);

                sheet.AutoFitColumns();
                //sheet.AutoFitRows();

                book.Save(outFileName);
            }
            catch (Exception e)
            {
                log.Error("导出Excel失败!" + e.Message);
                throw e;
            }
        }
    }
}


导入就不说了。导入为datetable之后就自己操作就OK。

 

//********************************************************************************

使用Aspose.Cells 设置Excel

 
步骤:
              1.WorkBookBase 继承自Aspose.Cells.Workbook,在WorkBookBase 中注册
              2.使用WorkBookBase 操作Excel
      /// <summary>
      /// 创建workBook许可
      /// </summary>
      /// <author>wxl</author>
      /// <date>2012-10-15</date>
      public class WorkBookBase : Aspose.Cells.Workbook
      {
              public WorkBookBase()
              {
                      Aspose.Cells.License license = new Aspose.Cells.License();

                      string strLic = @"<License>
                                                                  <Data>
                                                                      <SerialNumber>aed83727-21cc-4a91-bea4-2607bf991c21</SerialNumber>
                                                                      <EditionType>Enterprise</EditionType>
                                                                      <Products>
                                                                          <Product>Aspose.Total</Product>
                                                                      </Products>
                                                                  </Data>
                                                                  <Signature>CxoBmxzcdRLLiQi1kzt5oSbz 9GhuyHHOBgjTf5w/wJ1V+lzjBYi8o7PvqRwkdQo4tT4dk 3PIJPbH9w5Lszei1SV/smkK8SCjR8kIWgLbOUFBvhD1 Fn9KgDAQ8B11psxIWvepKidw 8ZmDmbk9kdJbVBOkuAESXDdt DEDZMB/zL7Y=</Signature>
                                                              </License>";

                      MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(strLic));
                      license.SetLicense(ms);
 
             
Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//单元格

sheet.Protect(ProtectionType.All, "123123", "");//保护工作表
sheet.Protection.IsSelectingLockedCellsAl lowed = false;//设置只能选择解锁单元格
sheet.Protection.IsFormattingColumnsAllow ed = true;//设置可以调整列
sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行

Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style1.Font.Name = "宋体";//文字字体
style1.Font.Size = 12;//文字大小
style1.IsLocked = false;//单元格解锁
style1.Font.IsBold = true;//粗体
style1.ForegroundColor = Color.FromArgb(0x99, 0xcc, 0xff);//设置背景色
style1.Pattern = BackgroundType.Solid; //设置背景样式
style1.IsTextWrapped = true;//单元格内容自动换行
style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
//设置单元格背景颜色
style1.ForegroundColor  =  System.Drawing.Color.FromArgb( 153 204 0 );
style1.Pattern 
=  BackgroundType.Solid;

cells.Merge(0, 0, 1, 5);//合并单元格
cells[0, 0].PutValue("内容");//填写内容
cells[0, 0].SetStyle(style1);//给单元格关联样式
//cells[0,0].Style=style1; //给单元格关联样式
                                             
cells.SetRowHeight(0, 38);//设置行高

cells.SetColumnWidth(1, 20);//设置列宽

  cells[1, 0].Formula = "=AVERAGE(B1:E1)";//给单元格设置计算公式

  System.IO.MemoryStream ms = workbook.SaveToStream();//生成数据流
  byte[] bt = ms.ToArray();

  workbook.Save(@"D:\test.xls");//保存到硬盘

 

//***********************************************************************************************

基于Aspose.Cells.dll 封装了对于导出的Excel的各种样式设置,内容填充操作,目前支持边框样式,颜色,字体,合并单元格等操作,简化Aspose.Cells.dll的使用

调用示例

        /// ---------->Clom Y
        /// |
        /// |
        /// |
        /// \/ Row X
        static void Main(string[] args)
        {
            object[] clom = { "列名1", "列名2", "列名3" };
            object[] row = { "行名1", "行名2", "行名3", "行名4" };
            String filename = "text.xlsx";

            //列标题样式
            CellStyle Styleclom = new CellStyle();
            Styleclom.AllBorder = Aspose.Cells.CellBorderType.Thin;
            Styleclom.ForegroundColor = Color.Yellow;
            Styleclom.IsBold = true;
            //行标题样式
            CellStyle Stylerow = new CellStyle();
            Stylerow.AllBorder = Aspose.Cells.CellBorderType.Thin;
            Stylerow.ForegroundColor = Color.ForestGreen;
            Stylerow.IsBold = true;
            //单元格样式
            CellStyle Stylebody = new CellStyle();
            Stylebody.AllBorder = Aspose.Cells.CellBorderType.Medium;
            Stylebody.ForegroundColor = Color.LightBlue;
            Stylebody.IsBold = true;
            Stylebody.IsItalic = true;

            //将样式和内容填充到模板中
            ExcelFormat eformat = new ExcelFormat();
            eformat.SavePath = filename;
            eformat.ColumnsSize = 20;
            eformat.RowsSize = 20;
            //直接插入标题
            //eformat.InsertTitle(clom.ToList(), Styleclom,  ExcelFormat.TitleType.列标题);
            //eformat.InsertTitle(row.ToList(), Stylerow, ExcelFormat.TitleType.行标题);

            eformat.InsertCellRow(new CellRow(1, 4, 0, clom.ToList()), Stylerow);
            eformat.InsertCellColm(new CellColm(1, 5, 0, row.ToList()), Styleclom);

            for (int i = 0; i < clom.Length; i++)
            {
                for (int j = 0; j < row.Length; j++)
                {
                    SCell scell = new SCell();
                    scell.Txt_Obj = Convert.ToString(row[j]) + Convert.ToString(row[i]);
                    scell.X = j + 1;
                    scell.Y = i + 1;
                    scell.CStyle = Stylebody;
                    eformat.SCells.Add(scell);
                }
            }
            //向Excel中写入数据
            ExcelMethod.InsertData(eformat, true);

            Console.WriteLine("完毕");
            Console.ReadLine();
        }

导出例子
这里写图片描述

GitHub地址

2017/11/15更新后 不再对所谓的标题行标题列作区分(在ExcelFormat对象中只保留SCells属性,即可配置样式的单元格集合。除此之外,新增了数据行,数据列,数据区块的概念,方便一组规则且具有相同样式的数据区块插入。为确保配置样式和插入的灵活性,所有的单元格最终汇总到SCells中等待写入)

//********************************************************************************

Aspose.cell.dll的使用,导excel表

 

using System;
using System.Web;
using EF;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq; using System.IO; using Aspose.Cells; //using Microsoft.Office.Interop.Excel; //using System.Reflection; public class ToOverTimexls : IHttpHandler {     public void ProcessRequest(HttpContext context)     {         int oname = 0, years = 0, month = 0;         if (context.Request["name"] != null)         {             oname = int.Parse(context.Request["name"]);         }         if (context.Request["years"] != null)         {             years = int.Parse(context.Request["years"]);         }         if (context.Request["month"] != null)         {             month = int.Parse(context.Request["month"]);         }         //oname = 1; years = 2016; month = 1;         using (WorkRecordEntities db = new WorkRecordEntities())         {             IList<OverTime> list = db.OverTime.Where(o => o.StaffID == oname && o.StartTime.Year == years && o.StartTime.Month == month).ToList();             var name = db.Staff.Where(o => o.StaffID == oname).FirstOrDefault().FullName;             //建立一个Excel进程 Application             // string SavaFilesPath = System.Configuration.ConfigurationManager.AppSettings["DownLoad"] + Guid.NewGuid() + ".xls";             string SavaFilesPath = context.Server.MapPath("~/Download") + "\\" + Guid.NewGuid() + ".xls";             // Application excelApplication = new Application();             // //默认值为 True。如果不想在宏运行时被无穷无尽的提示和警告消息所困扰,请将本属性设置为 False;这样每次出现需用户应答的消息时,Microsoft Excel             // // 将选择默认应答。             // //如果将该属性设置为 False,则在代码运行结束后,Micorosoft Excel 将该属性设置为 True,除非正运行交叉处理代码。             // //如果使用工作簿的 SaveAs 方法覆盖现有文件,“覆盖”警告默认为“No”,当 DisplayAlerts 属性值设置为 True 时,Excel 选择“Yes”。             // excelApplication.DisplayAlerts = false;             // //  建立或打开一个 Workbook对象生成新Workbook             // Workbook workbook = excelApplication.Workbooks.Add(Missing.Value);             // //int x = 2;             // Worksheet lastWorksheet = (Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);             // Worksheet newSheet = (Worksheet)workbook.Worksheets.Add(Type.Missing, lastWorksheet, Type.Missing, Type.Missing);             // //表头             // newSheet.Cells[4, 1] = "No.(序号)";             // newSheet.Cells[4, 2] = "Date(日期)";             // newSheet.Cells[4, 3] = "Mon.~Sun.";             // newSheet.Cells[4, 4] = "From(开始)";             // newSheet.Cells[4, 5] = "To(止)";             // newSheet.Cells[4, 6] = "OT Hrs.(时间)";             // newSheet.Cells[4, 7] = "Evnt(加班事由)";             // newSheet.Cells[4, 8] = "Approve(审批)";             // newSheet.Cells[3, 4] = "To(加班时间)";             // newSheet.Cells[1,4]="加班申请表";             // newSheet.Cells[2,1]="部门:后台";              newSheet.Cells[2, 2] = "后台";             // newSheet.Cells[2, 6] = "姓名:"+name;             // //newSheet.Cells[2, 7] = name;             // newSheet.get_Range("A1", "H1").Merge(newSheet.get_Range("A1", "H1").MergeCells);             // newSheet.get_Range("A2", "D2").Merge(newSheet.get_Range("A2", "D2").MergeCells);             // newSheet.get_Range("F2", "H2").Merge(newSheet.get_Range("F2", "H2").MergeCells);             // newSheet.get_Range("A3", "A4").Merge(newSheet.get_Range("A3", "A4").MergeCells);             // newSheet.get_Range("B3", "B4").Merge(newSheet.get_Range("B3", "B4").MergeCells);             // newSheet.get_Range("C3", "C4").Merge(newSheet.get_Range("C3", "C4").MergeCells);             // newSheet.get_Range("D3", "F3").Merge(newSheet.get_Range("D3", "F3").MergeCells);             // newSheet.get_Range("G3", "G4").Merge(newSheet.get_Range("G3", "G4").MergeCells);             // newSheet.get_Range("H3", "H4").Merge(newSheet.get_Range("H3", "H4").MergeCells);             // newSheet.get_Range("A3", "H3").Interior.ColorIndex = 15;             // newSheet.get_Range("A4", "H4").Interior.ColorIndex = 15;             // Range range1 = newSheet.get_Range("A1", "H1");             // range1.HorizontalAlignment = XlHAlign.xlHAlignCenter;             // range1.WrapText = true;             // Range range = newSheet.get_Range("A3", "H4");             // range.HorizontalAlignment = XlHAlign.xlHAlignCenter;             // range.Font.Size = 10;             // range.Borders.LineStyle = 1;             // //设置边框                      range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());                     // range.Borders.get_Item(XlBordersIndex.xlEdgeBottom).Weight = XlBorderWeight.xlMedium;             // range.WrapText = true;              var x = 3;             // var x = 5;             // for (var i = 0; i < list.Count; i++)             // {             //     newSheet.Cells[x + i, 1] = i + 1;             //     newSheet.Cells[x + i, 2] = list[i].StartTime.Month + "月" + list[i].StartTime.Day + "日";             //     newSheet.Cells[x + i, 3] = GetWeekCHA((list[i].StartTime.DayOfWeek).ToString());             //     newSheet.Cells[x + i, 4] = list[i].StartTime.ToString("yyyy/MM/dd HH:mm:ss");             //     newSheet.Cells[x + i, 5] = list[i].EndTime.ToString("yyyy/MM/dd HH:mm:ss");             //     int ts = (list[i].EndTime - list[i].StartTime).Hours;             //     newSheet.Cells[x + i, 6] = ts;             //     newSheet.Cells[x + i, 7] = list[i].Description;             //     newSheet.Cells[x + i, 8] = "";             // }             // newSheet.Cells.Columns.AutoFit();             // //删除原来的空Sheet             // ((Worksheet)workbook.Worksheets.get_Item(1)).Delete();             // ((Worksheet)workbook.Worksheets.get_Item(1)).Delete();             // ((Worksheet)workbook.Worksheets.get_Item(1)).Delete();             // //设置默认选中是第一个Sheet 类似于Select();             // ((Worksheet)workbook.Worksheets.get_Item(1)).Activate();             // try             // {             //     workbook.Close(true, SavaFilesPath, Missing.Value);             // }             // catch (Exception e)             // {             //     throw e;             // }             // UploadExcel(SavaFilesPath, true);             // excelApplication.Quit();             Workbook workbook = new Workbook();             Worksheet worksheet = workbook.Worksheets[0];             Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式                styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中             worksheet.PageSetup.Orientation = PageOrientationType.Landscape;//横向打印             worksheet.PageSetup.Zoom = 100;//以100%的缩放模式打开             worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4;             Range range; Cell cell;             range = worksheet.Cells.CreateRange(0, 0, 1, 8);             range.Merge();             range.RowHeight = 20;             range.ColumnWidth = 15;             cell = range[0, 0];             cell.PutValue("加班申请表");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(1, 0, 1, 2);             range.Merge();             range.RowHeight = 15;             cell = range[0, 0];             cell.PutValue("部门:后台");             range = worksheet.Cells.CreateRange(1, 4, 1, 2);             range.Merge();             range.RowHeight = 15;             cell = range[0, 0];             cell.PutValue("姓名:" + name);             //range = worksheet.Cells.CreateRange(1, 5, 1, 1);             //range.Merge();             //range.RowHeight = 15;             //cell = range[0, 0];             //cell.PutValue("方亭");             range = worksheet.Cells.CreateRange(2, 0, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("No.(序号)");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 1, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("Date(日期)");             range = worksheet.Cells.CreateRange(2, 2, 2, 1);             range.Merge();                          cell = range[0, 0];             cell.PutValue("Mon.~Sun.");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 3, 1, 3);             range.Merge();             range.ColumnWidth = 20;                          cell = range[0, 0];             cell.PutValue("To(加班时间)");             cell.SetStyle(styleTitle);             cell = worksheet.Cells[3, 3];             cell.PutValue("From(开始)");             cell.SetStyle(styleTitle);             cell = worksheet.Cells[3, 4];             cell.PutValue("To(止)");             cell.SetStyle(styleTitle);             cell = worksheet.Cells[3, 5];             cell.PutValue("OT Hrs.(时间)");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 6, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("Evnt(加班事由)");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 7, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("Approve(审批)");             cell.SetStyle(styleTitle);             for (var i = 0; i < list.Count; i++)             {                 //newSheet.Cells[x + i, 1] = i + 1;                 //newSheet.Cells[x + i, 2] = list[i].StartTime.Month + "月" + list[i].StartTime.Day + "日";                 //newSheet.Cells[x + i, 3] = GetWeekCHA((list[i].StartTime.DayOfWeek).ToString());                 //newSheet.Cells[x + i, 4] = list[i].StartTime.ToString("yyyy/MM/dd HH:mm:ss");                 //newSheet.Cells[x + i, 5] = list[i].EndTime.ToString("yyyy/MM/dd HH:mm:ss");                 //int ts = (list[i].EndTime - list[i].StartTime).Hours;                 //newSheet.Cells[x + i, 6] = ts;                 //newSheet.Cells[x + i, 7] = list[i].Description;                 //newSheet.Cells[x + i, 8] = "";                 cell = worksheet.Cells[4 + i, 0];                 cell.PutValue(i + 1);                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 1];                 cell.PutValue(list[i].StartTime.Month + "月" + list[i].StartTime.Day + "日");                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 2];                 cell.PutValue(GetWeekCHA((list[i].StartTime.DayOfWeek).ToString()));                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 3];                 cell.PutValue(list[i].StartTime.ToString("yyyy/MM/dd HH:mm:ss"));                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 4];                 cell.PutValue(list[i].EndTime.ToString("yyyy/MM/dd HH:mm:ss"));                 cell.SetStyle(styleTitle);                 int ts = (list[i].EndTime - list[i].StartTime).Hours;                 cell = worksheet.Cells[4 + i, 5];                 cell.PutValue(ts);                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 6];                 cell.PutValue(list[i].Description);                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 7];                 cell.PutValue("");                 cell.SetStyle(styleTitle);             }             workbook.Save(SavaFilesPath);             UploadExcel(SavaFilesPath, true);         }     }     ///   <summary>        ///   返回星期中文名        ///   </summary>        ///   <param   name="WeekENG">星期英文名</param>        ///   <returns></returns>        public string GetWeekCHA(string WeekENG)     {         string return_value = "";         switch (WeekENG)         {             case "Monday":                 return_value = "星期一";                 return return_value;             case "Tuesday":                 return_value = "星期二";                 return return_value;             case "Wednesday":                 return_value = "星期三";                 return return_value;             case "Thursday":                 return_value = "星期四";                 return return_value;             case "Friday":                 return_value = "星期五";                 return return_value;             case "Saturday":                 return_value = "星期六";                 return return_value;             case "Sunday":                 return_value = "星期日";                 return return_value;         }         return return_value;     }     /// <summary>     /// 提供下载     /// </summary>     /// <param name="path"></param>     /// <param name="page"
   //下载Excel
            window.location.href = "/ashx/ToExcel.ashx?project=" + probject + "&years=" + years + "&month=" + month;

    
    

 

//**************************************************************************************************

C# 读写Excel的一些方法,Aspose.Cells.dll

需求:现有2个Excel,一个7000,一个20W,7000在20W是完全存在的。现要分离20W的,拆分成19W3和7000。

条件:两个Excel都有“登录名”,然后用“登录名”去关联2个Excel

引用:Aspose.Cells.dll

复制代码
public void Excel()
{ 
    //获取第一个Excel,20W
    string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/测试20W.xlsx";
    System.Data.DataTable table = GetTableFromExcel("sheet1", filePath);

    //克隆
    System.Data.DataTable table20W_new = table.Clone();
    System.Data.DataTable table7000_new = table.Clone();    

    //获取第二个Excel,7000
    string filePath_7000 = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/测试7000.xls";
    System.Data.DataTable table_7000 = GetTableFromExcel("sheet1", filePath_7000);

    //循环20W人中的挑出来
    for (int i = 0; i < table.Rows.Count; ++i)
    {
        //20W
        DataRow dateRow = table.Rows[i];
        string login_name = dateRow["登录名"].ToString();

        //7000
        DataRow[] drss = table_7000.Select("登录名 = '" + login_name + "'");
     
        if (drss.Length > 0)
        {
            table7000_new.ImportRow(dateRow);
        }
        else
        {
            table20W_new.ImportRow(dateRow);
        }
    }
    //导出Excel
    DataTableExport(table7000_new, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/7000.xlsx");
    DataTableExport(table20W_new, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/22W.xlsx");
}
复制代码

获取Excel内容,转成DataTable。

复制代码
/// <summary>
/// 获取Excel内容。
/// </summary>
/// <param name="sheetName">工作表名称,例:sheet1</param>
/// <param name="filePath">Excel路径</param>
/// <returns></returns>
private DataTable GetTableFromExcel(string sheetName, string filePath)
{
    const string connStrTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;\"";
    DataTable dt = null;
    if (!System.IO.File.Exists(filePath))
    {
        // don't find file
        return null;
    }
    OleDbConnection conn = new OleDbConnection(string.Format(connStrTemplate, filePath));
    try
    {
        conn.Open();
        if (sheetName == null || sheetName.Trim().Length == 0)
        {
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
        }
        else
        {
            sheetName += "$";
        }

        string strSQL = "Select * From [" + sheetName + "]";
        OleDbDataAdapter da = new OleDbDataAdapter(strSQL, conn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        dt = ds.Tables[0];
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        conn.Close();
    }

    return dt;
}
复制代码

将DataTable的数据写进Excel里(用的Aspose.Cells.dll)

复制代码
/// <summary>
/// DataTable数据导出Excel
/// </summary>
/// <param name="data"></param>
/// <param name="filepath"></param>
public static void DataTableExport(DataTable data, string filepath)
{
    try
    {
        Workbook book = new Workbook();
        Worksheet sheet = book.Worksheets[0];
        Cells cells = sheet.Cells;

        int Colnum = data.Columns.Count;//表格列数 
        int Rownum = data.Rows.Count;//表格行数 
        //生成行 列名行 
        for (int i = 0; i < Colnum; i++)
        {
            cells[0, i].PutValue(data.Columns[i].ColumnName);
        }
        //生成数据行 
        for (int i = 0; i < Rownum; i++)
        {
            for (int k = 0; k < Colnum; k++)
            {
                cells[1 + i, k].PutValue(data.Rows[i][k].ToString());
            }
        }
        book.Save(filepath);
        GC.Collect();
    }
    catch (Exception e)
    {
        logger.Error("生成excel出错:" + e.Message);
    }
}
复制代码

将List的数据写进Excel里(用的Aspose.Cells.dll)

复制代码
/// <summary>
/// 导出excel  
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">Ilist集合</param>
/// <param name="filepath">保存的地址</param>
public static void Export<T>(IList<T> data, string filepath)
{
    try
    {
        Workbook workbook = new Workbook();
        Worksheet sheet = (Worksheet)workbook.Worksheets[0];

        PropertyInfo[] ps = typeof(T).GetProperties();
        var colIndex = "A";
        foreach (var p in ps)
        {
            //    sheet.Cells[colIndex + 1].PutValue(p.Name);//设置表头名称  要求表头为中文所以不用 p.name 为字段名称 可在list第一条数据为表头名称
            int i = 1;
            foreach (var d in data)
            {
                sheet.Cells[colIndex + i].PutValue(p.GetValue(d, null));
                i++;
            }
            colIndex = getxls_top(colIndex); //((char)(colIndex[0] + 1)).ToString();//表头  A1/A2/
        }
        //workbook.Shared = true;
        workbook.Save(filepath);
        GC.Collect();
    }
    catch (Exception e)
    {
        logger.Error("生成excel出错:" + e.Message);
    }
}
/// <summary>
/// 生成新的对应的列  A-Z  AA-ZZ
/// </summary>
/// <param name="top">当前列</param>
/// <returns></returns>
private static string getxls_top(string top)
{
    char[] toplist = top.ToArray();
    var itemtop = top.Last();
    string topstr = string.Empty;
    if ((char)itemtop == 90)//最后一个是Z
    {
        if (toplist.Count() == 1)
        {
            topstr = "AA";
        }
        else
        {
            toplist[0] = (char)(toplist[0] + 1);
            toplist[toplist.Count() - 1] = 'A';
            foreach (var item in toplist)
            {
                topstr += item.ToString();
            }
        }
    }
    else//最后一个不是Z  包括top为两个字符
    {
        itemtop = (char)(itemtop + 1);
        toplist[toplist.Count() - 1] = itemtop;

        foreach (var item in toplist)
        {
            topstr += item.ToString();
        }
    }
    return topstr;
}
复制代码

将DataTable的数据写进Excel里(用的Microsoft.Office.Interop.Excel.dll)(此方法在大量数据的时候很慢,例如22W条数据,建议使用Aspose.Cells.dll,速度快很多)

复制代码
/// <summary>
/// 将DataTable的数据写进Excel里
/// </summary>
/// <param name="tmpDataTable">DataTable数据</param>
/// <param name="strFileName">Excel路径</param>
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
    if (tmpDataTable == null)
    {
        return;
    }
    int rowNum = tmpDataTable.Rows.Count;
    int columnNum = tmpDataTable.Columns.Count;
    int rowIndex = 1;
    int columnIndex = 0;

    //需要引用Microsoft.Office.Interop.Excel.dll
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
    xlApp.DefaultFilePath = "";
    xlApp.DisplayAlerts = true;
    xlApp.SheetsInNewWorkbook = 1;
    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);

    //将DataTable的列名导入Excel表第一行
    foreach (DataColumn dc in tmpDataTable.Columns)
    {
        columnIndex++;
        xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
    }

    //将DataTable中的数据导入Excel中
    for (int i = 0; i < rowNum; i++)
    {
        rowIndex++;
        columnIndex = 0;
        for (int j = 0; j < columnNum; j++)
        {
            columnIndex++;
            xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
        }
    }

    //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
    xlBook.SaveCopyAs(strFileName);
}
复制代码

原生的DataTable生成Excel(无需引用第三方dll)

复制代码
/// <summary>
/// 将DataTable的数据写进Excel里
/// </summary>
/// <param name="tdKeChengZhuanJiaTongJi">DataTable</param>
/// <param name="sheet">sheet自定义名称</param>
/// <param name="fileName">Excel路径</param>
public static void DataTabletoExcel(DataTable dt, string sheet, string fileName)
{
    String sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0 Xml;\"";
    //string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;'";
    //String sConnectionString = "Provider=Microsoft.ACE.OLEDB.14.0;Data Source=" + fileName + ";Extended Properties=\"Excel 14.0 Xml;\"";
    //String sConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + fileName + ";Extended Properties=\"Excel 16.0 Xml;HDR=YES;\"";

    OleDbConnection cn = new OleDbConnection(sConnectionString);

    int rowNum = dt.Rows.Count;//获取行数
    int colNum = dt.Columns.Count;//获取列数
    string sqlText = "";//带类型的列名
    string sqlValues = "";//
    string colCaption = "";//列名
    for (int i = 0; i < colNum; i++)
    {
        if (i != 0)
        {
            sqlText += " , ";
            colCaption += " , ";
        }
        sqlText += "[" + dt.Columns[i].Caption.ToString() + "] VarChar";//生成带VarChar列的标题
        colCaption += "[" + dt.Columns[i].Caption.ToString() + "]";//生成列的标题
    }
    try
    {
        //打开连接
        cn.Open();
        string sqlCreate = "CREATE TABLE [" + sheet.ToString() + "] (" + sqlText + ")";
        OleDbCommand cmd = new OleDbCommand(sqlCreate, cn);
        //创建Excel文件
        cmd.ExecuteNonQuery();
        for (int srow = 0; srow < rowNum; srow++)
        {
            sqlValues = "";
            for (int col = 0; col < colNum; col++)
            {
                if (col != 0)
                {
                    sqlValues += " , ";
                }
                sqlValues += "'" + dt.Rows[srow][col].ToString() + "'";//拼接Value语句
            }
            String queryString = "INSERT INTO [" + sheet.ToString() + "] (" + colCaption + ") VALUES (" + sqlValues + ")";
            cmd.CommandText = queryString;
            cmd.ExecuteNonQuery();//插入数据
        }
    }
    catch
    {
    //生成日志
    }
    finally
    {
        cn.Close();
    }
}

 

 

//***************************************************************************************************

C# WinForm 导出导入Excel/Doc 完整实例教程[使用Aspose.Cells.dll]

[csharp] view plain copy print ?
  1. 1.添加引用:  
  2.   
  3. Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载。关于它的操作我在“Aspose.Cells操作说明 中文版 下载 Aspose C# 导出Excel 实例”一文中的说。这里你暂时也可不理会它。)  
  4. 即使没有安装office也能用噢,这是一个好强的大工具。  
  5. 2.编写Excel操作类  
  6.   
  7. using System;  
  8. using System.Collections.Generic;  
  9. using System.Text;  
  10. using Aspose.Cells;  
  11. using System.Data;  
  12. public class AsposeExcel  
  13. {  
  14.     private string outFileName = "";  
  15.     private string fullFilename = "";  
  16.     private Workbook book = null;  
  17.     private Worksheet sheet = null;  
  18.     public AsposeExcel(string outfilename, string tempfilename) //导出构造数  
  19.     {  
  20.         outFileName = outfilename;  
  21.         book = new Workbook();  
  22.         // book.Open(tempfilename);这里我们暂时不用模板  
  23.         sheet = book.Worksheets[0];  
  24.     }  
  25.     public AsposeExcel(string fullfilename) //导入构造数  
  26.     {  
  27.         fullFilename = fullfilename;  
  28.         // book = new Workbook();  
  29.         // book.Open(tempfilename);  
  30.         // sheet = book.Worksheets[0];  
  31.     }  
  32.     private void AddTitle(string title, int columnCount)  
  33.     {  
  34.         sheet.Cells.Merge(0, 0, 1, columnCount);  
  35.         sheet.Cells.Merge(1, 0, 1, columnCount);  
  36.         Cell cell1 = sheet.Cells[0, 0];  
  37.         cell1.PutValue(title);  
  38.         cell1.Style.HorizontalAlignment = TextAlignmentType.Center;  
  39.         cell1.Style.Font.Name = "黑体";  
  40.         cell1.Style.Font.Size = 14;  
  41.         cell1.Style.Font.IsBold = true;  
  42.         Cell cell2 = sheet.Cells[1, 0];  
  43.         cell1.PutValue("查询时间:" + DateTime.Now.ToLocalTime());  
  44.         cell2.SetStyle(cell1.Style);  
  45.     }  
  46.     private void AddHeader(DataTable dt)  
  47.     {  
  48.         Cell cell = null;  
  49.         for (int col = 0; col < dt.Columns.Count; col++)  
  50.         {  
  51.             cell = sheet.Cells[0, col];  
  52.             cell.PutValue(dt.Columns[col].ColumnName);  
  53.             cell.Style.Font.IsBold = true;  
  54.         }  
  55.     }  
  56.     private void AddBody(DataTable dt)  
  57.     {  
  58.         for (int r = 0; r < dt.Rows.Count; r++)  
  59.         {  
  60.             for (int c = 0; c < dt.Columns.Count; c++)  
  61.             {  
  62.                 sheet.Cells[r + 1, c].PutValue(dt.Rows[R]­[c].ToString());  
  63.             }  
  64.         }  
  65.     }  
  66.     //导出------------下一篇会用到这个方法  
  67.     public Boolean DatatableToExcel(DataTable dt)  
  68.     {  
  69.         Boolean yn = false;  
  70.         try  
  71.         {  
  72.             //sheet.Name = sheetName;  
  73.             //AddTitle(title, dt.Columns.Count);  
  74.             //AddHeader(dt);  
  75.             AddBody(dt);  
  76.             sheet.AutoFitColumns();  
  77.             //sheet.AutoFitRows();  
  78.             book.Save(outFileName);  
  79.             yn = true;  
  80.             return yn;  
  81.         }  
  82.         catch (Exception e)  
  83.         {  
  84.             return yn;  
  85.             // throw e;  
  86.         }  
  87.     }  
  88.     public DataTable ExcelToDatatalbe()//导入  
  89.     {  
  90.         Workbook book = new Workbook();  
  91.         book.Open(fullFilename);  
  92.         Worksheet sheet = book.Worksheets[0];  
  93.         Cells cells = sheet.Cells;  
  94.         //获取excel中的数据保存到一个datatable中  
  95.         DataTable dt_Import = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, false);  
  96.         // dt_Import.  
  97.         return dt_Import;  
  98.     }  
  99. }[/R]  
  100.   
  101. 3. Word导出  
  102. //设置文件类型  
  103. // saveFileDialog为一个对话框控件  
  104. //如果没有人工具栏中拉,  
  105. //可以:SaveFileDialog saveFileDialog1=new SaveFileDialog();  
  106. saveFileDialog1.Filter = "导出Excel (*.xls)|*.xls|Word (*.doc)|*.doc";  
  107. saveFileDialog1.FilterIndex = 1;  
  108. saveFileDialog1.RestoreDirectory = true;  
  109. saveFileDialog1.CreatePrompt = true;  
  110. saveFileDialog1.Title = "导出文件保存路径";  
  111. //saveFileDialog1.ShowDialog();  
  112. //string strName = saveFileDialog1.FileName;  
  113. //设置默认文件类型显示顺序  
  114. //saveFileDialog1.FilterIndex = 2;  
  115. //保存对话框是否记忆上次打开的目录  
  116. saveFileDialog1.RestoreDirectory = true;  
  117. //点了保存按钮进入  
  118. if (saveFileDialog1.ShowDialog() == DialogResult.OK)  
  119. {  
  120.     //获得文件路径  
  121.     string localFilePath = saveFileDialog1.FileName.ToString();  
  122.     //获取文件名,不带路径  
  123.     string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);  
  124.     //获取文件路径,不带文件名  
  125.     string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));  
  126.     //给文件名前加上时间  
  127.     string newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;  
  128.     //在文件名里加字符  
  129.     //saveFileDialog1.FileName.Insert(1,"dameng");  
  130.     saveFileDialog1.FileName = FilePath + "\\" + newFileName;  
  131.     System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//输出文件  
  132.     StreamWriter writer = new StreamWriter(fs);  
  133.     writer.Write("tttt");//这里就是你要导出到word的内容,内容是你什么你自已DIY  
  134.     writer.Flush();  
  135.     writer.Close();  
  136.     fs.Close();  
  137. }  
  138.   
  139. 4. 导出datatable到excel  
  140.   
  141. DataTable dt = null;  
  142. if (ds_all.Tables[0] != null)  
  143. {  
  144.     dt = ds_all.Tables[0];  
  145. }  
  146. else {  
  147.     MessageBox.Show("没有数据记录""*^_^* 温馨提示信息", MessageBoxButtons.OK);  
  148.     return;  
  149. }  
  150. //上面只是取datatable,你自己diy  
  151. AsposeExcel tt = new AsposeExcel(saveFileDialog1.FileName, "");//不用模板, saveFileDialog1是什么?上面已经说过  
  152. bool OK_NO = tt.DatatableToExcel(dt);  
  153. if (OK_NO)  
  154. {  
  155.     MessageBox.Show("导出成功""*^_^* 温馨提示信息", MessageBoxButtons.OK);  
  156. }  
  157. else  
  158. {  
  159. }  
  160.   
  161. 5. Excel导入  
  162. private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)  
  163. {  
  164.     string localFilePath = "";  
  165.     //点了保存按钮进入  
  166.     if (openFileDialog1.ShowDialog() == DialogResult.OK)// openFileDialog1不要再问我这是什么!  
  167.     {  
  168.         //获得文件路径  
  169.         localFilePath = openFileDialog1.FileName.ToString();  
  170. }  
  171.     AsposeExcel tt = new AsposeExcel(localFilePath);  
  172.     DataTable dt;  
  173.     try  
  174.     {  
  175.         dt = tt.ExcelToDatatalbe();  
  176.     }  
  177.     catch (Exception ex)  
  178.     {  
  179.         return;  
  180.     }  
  181. //有了datatable你自己就可以DIY啦,下面是我自己的你不用理  
  182. if (ddlResidence.SelectedValue == "违章确认")  
  183.     {  
  184.         if (dt.Rows[0][9].ToString() != "违章确认")  
  185.         {  
  186.                             return;  
  187.         }  
  188.         row = dt.Rows.Count;  
  189.         if (row <= 0) return;  
  190.         for (int i = 0; i < dt.Rows.Count; i++)  
  191.         {  
  192.             bllviola.Up_Confirmed_ByVnum(dt.Rows[i][6].ToString(), dt.Rows[i][9].ToString());  
  193.         }  
  194.         this.GridView1.DataSource = dt;  
  195.         GridView1.DataBind();  
  196. }  
1.添加引用:

Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载。关于它的操作我在“Aspose.Cells操作说明 中文版 下载 Aspose C# 导出Excel 实例”一文中的说。这里你暂时也可不理会它。)
即使没有安装office也能用噢,这是一个好强的大工具。
2.编写Excel操作类

using System;
using System.Collections.Generic;
using System.Text;
using Aspose.Cells;
using System.Data;
public class AsposeExcel
{
    private string outFileName = "";
    private string fullFilename = "";
    private Workbook book = null;
    private Worksheet sheet = null;
    public AsposeExcel(string outfilename, string tempfilename) //导出构造数
    {
        outFileName = outfilename;
        book = new Workbook();
        // book.Open(tempfilename);这里我们暂时不用模板
        sheet = book.Worksheets[0];
    }
    public AsposeExcel(string fullfilename) //导入构造数
    {
        fullFilename = fullfilename;
        // book = new Workbook();
        // book.Open(tempfilename);
        // sheet = book.Worksheets[0];
    }
    private void AddTitle(string title, int columnCount)
    {
        sheet.Cells.Merge(0, 0, 1, columnCount);
        sheet.Cells.Merge(1, 0, 1, columnCount);
        Cell cell1 = sheet.Cells[0, 0];
        cell1.PutValue(title);
        cell1.Style.HorizontalAlignment = TextAlignmentType.Center;
        cell1.Style.Font.Name = "黑体";
        cell1.Style.Font.Size = 14;
        cell1.Style.Font.IsBold = true;
        Cell cell2 = sheet.Cells[1, 0];
        cell1.PutValue("查询时间:" + DateTime.Now.ToLocalTime());
        cell2.SetStyle(cell1.Style);
    }
    private void AddHeader(DataTable dt)
    {
        Cell cell = null;
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            cell = sheet.Cells[0, col];
            cell.PutValue(dt.Columns[col].ColumnName);
            cell.Style.Font.IsBold = true;
        }
    }
    private void AddBody(DataTable dt)
    {
        for (int r = 0; r < dt.Rows.Count; r++)
        {
            for (int c = 0; c < dt.Columns.Count; c++)
            {
                sheet.Cells[r + 1, c].PutValue(dt.Rows[R]­[c].ToString());
            }
        }
    }
    //导出------------下一篇会用到这个方法
    public Boolean DatatableToExcel(DataTable dt)
    {
        Boolean yn = false;
        try
        {
            //sheet.Name = sheetName;
            //AddTitle(title, dt.Columns.Count);
            //AddHeader(dt);
            AddBody(dt);
            sheet.AutoFitColumns();
            //sheet.AutoFitRows();
            book.Save(outFileName);
            yn = true;
            return yn;
        }
        catch (Exception e)
        {
            return yn;
            // throw e;
        }
    }
    public DataTable ExcelToDatatalbe()//导入
    {
        Workbook book = new Workbook();
        book.Open(fullFilename);
        Worksheet sheet = book.Worksheets[0];
        Cells cells = sheet.Cells;
        //获取excel中的数据保存到一个datatable中
        DataTable dt_Import = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, false);
        // dt_Import.
        return dt_Import;
    }
}[/R]

3. Word导出
//设置文件类型
// saveFileDialog为一个对话框控件
//如果没有人工具栏中拉,
//可以:SaveFileDialog saveFileDialog1=new SaveFileDialog();
saveFileDialog1.Filter = "导出Excel (*.xls)|*.xls|Word (*.doc)|*.doc";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.Title = "导出文件保存路径";
//saveFileDialog1.ShowDialog();
//string strName = saveFileDialog1.FileName;
//设置默认文件类型显示顺序
//saveFileDialog1.FilterIndex = 2;
//保存对话框是否记忆上次打开的目录
saveFileDialog1.RestoreDirectory = true;
//点了保存按钮进入
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    //获得文件路径
    string localFilePath = saveFileDialog1.FileName.ToString();
    //获取文件名,不带路径
    string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);
    //获取文件路径,不带文件名
    string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
    //给文件名前加上时间
    string newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
    //在文件名里加字符
    //saveFileDialog1.FileName.Insert(1,"dameng");
    saveFileDialog1.FileName = FilePath + "\\" + newFileName;
    System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//输出文件
    StreamWriter writer = new StreamWriter(fs);
    writer.Write("tttt");//这里就是你要导出到word的内容,内容是你什么你自已DIY
    writer.Flush();
    writer.Close();
    fs.Close();
}

4. 导出datatable到excel

DataTable dt = null;
if (ds_all.Tables[0] != null)
{
    dt = ds_all.Tables[0];
}
else {
    MessageBox.Show("没有数据记录", "*^_^* 温馨提示信息", MessageBoxButtons.OK);
    return;
}
//上面只是取datatable,你自己diy
AsposeExcel tt = new AsposeExcel(saveFileDialog1.FileName, "");//不用模板, saveFileDialog1是什么?上面已经说过
bool OK_NO = tt.DatatableToExcel(dt);
if (OK_NO)
{
    MessageBox.Show("导出成功", "*^_^* 温馨提示信息", MessageBoxButtons.OK);
}
else
{
}

5. Excel导入
private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)
{
    string localFilePath = "";
    //点了保存按钮进入
    if (openFileDialog1.ShowDialog() == DialogResult.OK)// openFileDialog1不要再问我这是什么!
    {
        //获得文件路径
        localFilePath = openFileDialog1.FileName.ToString();
}
    AsposeExcel tt = new AsposeExcel(localFilePath);
    DataTable dt;
    try
    {
        dt = tt.ExcelToDatatalbe();
    }
    catch (Exception ex)
    {
        return;
    }
//有了datatable你自己就可以DIY啦,下面是我自己的你不用理
if (ddlResidence.SelectedValue == "违章确认")
    {
        if (dt.Rows[0][9].ToString() != "违章确认")
        {
                            return;
        }
        row = dt.Rows.Count;
        if (row <= 0) return;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            bllviola.Up_Confirmed_ByVnum(dt.Rows[i][6].ToString(), dt.Rows[i][9].ToString());
        }
        this.GridView1.DataSource = dt;
        GridView1.DataBind();
}


 

//****************************************************************************************************

Aspose.Cells小实例

Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet sheet = workbook.Worksheets[0];sheet.FreezePanes(1, 1, 1, 0);//冻结第一行sheet.Cells["A1"].PutValue("ID");sheet.Cells["B1"].PutValue("手机号码");sheet.Cells["C1"].PutValue("姓名");sheet.Cells["D1"].PutValue("出生年月");sheet.Cells["E1"].PutValue("性别");sheet.Cells["F1"].PutValue("订购份数");sheet.Cells["G1"].PutValue("运营产品ID");sheet.Cells["H1"].PutValue("订单状态");sheet.Cells["I1"].PutValue("订单成功时间");sheet.Cells["J1"].PutValue("批次ID");sheet.Cells["K1"].PutValue("支付方式");sheet.Cells["L1"].PutValue("错误代码");///TODO///设置列1为文本,因为这列全是数字而且很长,不处理会变成自然数了。///这里需要注意Style是设置风格,而StyleFlag是开关,所以即使你设置了Style,没有打开对应的StyleFlag一样没用Aspose.Cells.Style sc1 = workbook.Styles[workbook.Styles.Add()];sc1.ShrinkToFit = true;sc1.Number = 49;Aspose.Cells.StyleFlag scf1 = new Aspose.Cells.StyleFlag();scf1.ShrinkToFit = true;scf1.NumberFormat = true;Aspose.Cells.Column colomn1 = sheet.Cells.Columns[1];colomn1.ApplyStyle(sc1, scf1);dt =getDataTable();//得到DataTablesheet.Cells.ImportDataTable(dt, false, "A2");//从A2开始填充数据sheet.AutoFitColumns();//让各列自适应宽度,这个很有用。workbook.Save(fileName, Aspose.Cells.FileFormatType.Excel2007Xlsx, Aspose.Cells.SaveType.OpenInExcel, response);//输出

很多时候输出的数据排序或者显示的列并不一定和DataTable得到的列排序数据完全一致,那么我们可以简单处理一下:比如把上面的

引用内容 引用内容
///TODO///设置列1为文本,因为这列全是数字而且很长,不处理会变成自然数了。///这里需要注意Style是设置风格,而StyleFlag是开关,所以即使你设置了Style,没有打开对应的StyleFlag一样没用Aspose.Cells.Style sc1 = workbook.Styles[workbook.Styles.Add()];sc1.ShrinkToFit = true;sc1.Number = 49;Aspose.Cells.StyleFlag scf1 = new Aspose.Cells.StyleFlag();scf1.ShrinkToFit = true;scf1.NumberFormat = true;Aspose.Cells.Column colomn1 = sheet.Cells.Columns[1];colomn1.ApplyStyle(sc1, scf1);dt =getDataTable();//得到DataTable

替换成:

引用内容 引用内容
DataTable dt1=getDataTable();for (int i = 0; i < dt1.Rows.Count; i++){sheet.Cells[(i + 1), 0].PutValue(dt1.Rows[i]["create_time"].ToString());sheet.Cells[(i + 1), 1].PutValue(dt1.Rows[i]["holder_mobile"].ToString());sheet.Cells[(i + 1), 2].PutValue(dt1.Rows[i]["rec_name"].ToString());sheet.Cells[(i + 1), 3].PutValue(string.IsNullOrEmpty(dt1.Rows[i]["rec_sex"].ToString()) ? "" : (dt1.Rows[i]["rec_sex"].ToString() == "1") ? "男" : "女");sheet.Cells[(i + 1), 4].PutValue(dt1.Rows[i]["rec_birthday"].ToString());sheet.Cells[(i + 1), 5].PutValue(dt1.Rows[i]["base_product_code"].ToString());sheet.Cells[(i + 1), 6].PutValue(dt1.Rows[i]["sell_price"].ToString());sheet.Cells[(i + 1), 7].PutValue(dt1.Rows[i]["pay_count"].ToString());sheet.Cells[(i + 1), 8].PutValue(dt1.Rows[i]["ins_policy"].ToString());sheet.Cells[(i + 1), 9].PutValue(dt1.Rows[i]["ins_end_date"].ToString());sheet.Cells[(i + 1), 10].PutValue(Rondi.Insu.Management.Utility.StateEnum.OrderFrom(dt1.Rows[i]["order_from"].ToString()));sheet.Cells[(i + 1), 11].PutValue(Rondi.Insu.Management.Utility.StateEnum.OrderState(dt1.Rows[i]["order_state"].ToString()));}

 

//*************************************************************************************
  • 15
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: aspose.cells.rar 18.4.7 是一个文件压缩包,其中包含了 Aspose.Cells 的 18.4.7 版本的相关文件。Aspose.Cells 是一款强大的电子表格处理组件,可用于创建、读取、修改和保存 Excel 文件。 18.4.7 版本是 Aspose.Cells 的特定版本,其中包含了一些新功能、改进和 bug 修复。Aspose.Cells 可以通过该版本实现更好的性能和稳定性,提供更多的功能选项,提高用户体验。 该压缩包的 .rar 格式是一种常见的压缩文件格式,可以使用相应的解压软件将其解压缩。解压后,可以找到包含 Aspose.Cells 文件和示例代码的文件夹。 在使用 Aspose.Cells 18.4.7 进行开发时,需要将相应的 DLL 文件添加到项目引用中,并按照文档中的说明来调用和使用相应的 API。 Aspose.Cells 的功能非常强大,可以用于处理电子表格的各种操作,如读取和写入单元格数据、设置格式、合并拆分单元格、插入和删除行列、创建图表等。它还支持导入和导出各种文件格式,如 Excel、CSV、HTML 和 PDF。 总之,aspose.cells.rar 18.4.7 是 Aspose.Cells 特定版本的压缩文件,包含了相关文件和示例代码,通过使用这个版本,可以更好地利用 Aspose.Cells 的功能来进行电子表格处理和开发。 ### 回答2: aspose.cells.rar 18.4.7是一个文件压缩包,包含了Aspose.Cells 18.4.7版本的相关资源和文件。 Aspose.Cells是一个用于处理Excel文件的强大的Java组件。18.4.7代表了该组件的版本号,该版本是在2018年4月7日发布的。 这个压缩包中包含了Aspose.Cells库的所有相关的JAR文件,可以用于在Java项目中集成和使用Aspose.Cells的功能。通过引入这些JAR文件,开发者可以方便地操作Excel文件,如读取、写入、修改、格式化、计算、渲染等各种操作。 使用这个压缩包,开发人员可以轻松地在他们的Java应用程序中添加Excel文件的生成和处理功能。无论是在Windows、Linux还是其他支持Java运行环境的平台上,都可以使用Aspose.Cells来进行Excel文件的相关操作。 此外,Aspose.Cells还提供了丰富的API,例如可以操作单元格、行、列、工作表、图表等,也可以进行图像处理和数据导入导出等功能。这些功能可以帮助开发人员更好地处理和操作Excel文件,提高开发效率。 总之,aspose.cells.rar 18.4.7是包含Aspose.Cells 18.4.7版本相关资源和文件的压缩包,可以帮助开发人员在他们的Java项目中轻松使用和集成Aspose.Cells的功能。 ### 回答3: aspose.cells.rar 18.4.7是一个文件压缩包,其中包含了Aspose.Cells的版本18.4.7。Aspose.Cells是一个用于处理Excel文件的类库,提供了许多功能和工具来操作和操作Excel文件。 该压缩包中的内容主要是一些源代码文件、示例和文档。源代码文件是Aspose.Cells的核心库,它们包含了所有必要的类和方法来读取、修改和创建Excel文件。示例文件则展示了如何使用Aspose.Cells来解决各种常见的Excel处理任务,例如读取数据、设置格式和公式,以及生成图表等。而文档文件则是Aspose.Cells的用户指南和API文档,用于帮助开发者了解和使用该类库。 通过使用aspose.cells.rar 18.4.7,开发者可以方便地将Aspose.Cells集成到他们的应用程序中,从而实现Excel文件的各种操作。无论是在读取和分析数据,还是在将数据导出到Excel报表中,Aspose.Cells都提供了丰富的功能和灵活性。 总之,aspose.cells.rar 18.4.7是一个用于处理Excel文件的类库Aspose.Cells的压缩包,其中包含了源代码文件、示例和文档,开发者可以使用它来实现各种与Excel文件相关的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值