当前位置: 首页 > 工具软件 > Aspose.Cells > 使用案例 >

Aspose.Cells基础使用方法整理

权浩邈
2023-12-01

Aspose.Cells基础使用方法整理

Aspose.Cells PDF文档: http://download.csdn.net/detail/djk8888/9675095

Aspose.Cells. Demo示例库:http://download.csdn.net/detail/djk8888/9675142

本文配套源码:http://download.csdn.net/detail/djk8888/9677210

1.创建Workbook和Worksheet

Workbook wb = new Workbook();
wb.Worksheets.Clear();
wb.Worksheets.Add("New Worksheet1");//New Worksheet1是Worksheet的name
Worksheet ws = wb.Worksheets[0];

如果直接用下边两句则直接使用默认的第一个Worksheet:
Workbook wb = new Workbook();
Worksheet ws = wb.Worksheets[0];

2.给Cell赋值设置背景颜色并加背景色:cell1
Cell cell = ws.Cells[0, 0]; 
cell.PutValue("填充"); //必须用PutValue方法赋值 
cell.Style.ForegroundColor = Color.Yellow; 
cell.Style.Pattern = BackgroundType.Solid; 
cell.Style.Font.Size = 10; 
cell.Style.Font.Color = Color.Blue; 
//自定义格式: 
cell.Style.Custom = "ddd, dd mmmm 'yy"; 
//旋转字体: 
cell.Style.Rotation = 90;

3.设置Range并赋值加Style range1
int styleIndex = wb.Styles.Add(); 
Style style = wb.Styles[styleIndex]; 
style.ForegroundColor = Color.Yellow; 
style.Pattern = BackgroundType.Solid; 
style.Font.Size = 10;  
//从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.否则可能不生效。

4.使用Formula:
ws.Cells[0,0].PutValue(1);
ws.Cells[1,0].PutValue(20);
ws.Cells[2,0].Formula="SUM(A1:B1)";
wb.CalculateFormula(true);

Save Excel文件的时候必须调用CalculateFormula方法计算结果。

5.插入图片:
string imageUrl = System.Web.HttpContext.Current.Server.MapPath("~/images/log_topleft.gif");
ws.Pictures.Add(10, 10, imageUrl);

6.使用Validations: 
Cells cells = ws.Cells; 
cells[12, 0].PutValue("Please enter a number other than 0 to 10 in B1 to activate data validation:"); 
cells[12, 0].Style.IsTextWrapped = true; 
cells[12, 1].PutValue(5); 
Validations validations = totalSheet.Validations;
Validation validation = validations[validations.Add()]; 
//Set the data validation type
validation.Type = ValidationType.WholeNumber;
//Set the operator for the data validation
validation.Operator = OperatorType.Between;
//Set the value or expression associated with the data validation
validation.Formula1 = "0";
//the value or expression associated with the second part of the data validation
validation.Formula2 = "10";
validation.ShowError = true;
//Set the validation alert style
validation.AlertStyle = ValidationAlertType.Information;
//Set the title of the data-validation error dialog box
validation.ErrorTitle = "Error";
//Set the data validation error message
validation.ErrorMessage = " Enter value between 0 to 10";
//Set the data validation input message
validation.InputMessage = "Data Validation using Condition for Numbers";
validation.IgnoreBlank = true;
validation.ShowInput = true;
validation.ShowError = true;
//设置Validations的区域,因为现在要Validations的位置是12,1,所以下面设置对应的也要是12,1
 
CellArea cellArea; 
cellArea.StartRow = 12; 
cellArea.EndRow = 12; 
cellArea.StartColumn = 1; 
cellArea.EndColumn = 1; 
validation.AreaList.Add(cellArea);
 

/* 要注意 的地方Validations 也是和Range的Style一样,要新增的,否则不生效 */

Aspose.Cells PDF文档: http://download.csdn.net/detail/djk8888/9675095

Aspose.Cells. Demo示例库:http://download.csdn.net/detail/djk8888/9675142

本文配套源码:http://download.csdn.net/detail/djk8888/9677210

举例:
引用:Aspose.Cells.DLL 到项目中
using Aspose.Cells;
public class OperateExcel
{
        /// 导出的文件保存到这里
        private static string ExportFilesPath = System.Configuration.ConfigurationManager.AppSettings["exportFilesPath"].ToString();
        /// 将DataTable生成Excel
        public static string ExportToExcel(DataTable dtList, string fileName)
        {
            //这里是利用Aspose.Cells.dll 生成excel文件的
            string pathToFiles = System.Web.HttpContext.Current.Server.MapPath(ExportFilesPath);
            string etsName = ".xlsx";
            //获取保存路径
            string path = pathToFiles + fileName + etsName;
            Workbook wb = new Workbook();
            Worksheet ws = wb.Worksheets[0];
            Cells cell = ws.Cells;
            //设置行高
            //cell.SetRowHeight(0, 20);
            //表头样式
            Style stHeadLeft = wb.Styles[wb.Styles.Add()];
            stHeadLeft.HorizontalAlignment = TextAlignmentType.Left;       //文字居中
            stHeadLeft.Font.Name = "宋体";
            stHeadLeft.Font.IsBold = true;                                 //设置粗体
            stHeadLeft.Font.Size = 14;                                     //设置字体大小
            Style stHeadRight = wb.Styles[wb.Styles.Add()];
            stHeadRight.HorizontalAlignment = TextAlignmentType.Right;       //文字居中
            stHeadRight.Font.Name = "宋体";
            stHeadRight.Font.IsBold = true;                                  //设置粗体
            stHeadRight.Font.Size = 14;                                      //设置字体大小
            //内容样式
            Style stContentLeft = wb.Styles[wb.Styles.Add()];
            stContentLeft.HorizontalAlignment = TextAlignmentType.Left;
            stContentLeft.Font.Size = 10;
            Style stContentRight = wb.Styles[wb.Styles.Add()];
            stContentRight.HorizontalAlignment = TextAlignmentType.Right;
            stContentRight.Font.Size = 10;
            //赋值给Excel内容
            for (int col = 0; col < dtList.Columns.Count; col++)
            {
                Style stHead = null;
                Style stContent = null;
                //设置表头
                string columnType = dtList.Columns[col].DataType.ToString();
                switch (columnType.ToLower())
                {
                    //如果类型是string,则靠左对齐(对齐方式看项目需求修改)
                    case "system.string":
                        stHead = stHeadLeft;
                        stContent = stContentLeft;
                        break;
                    default:
                        stHead = stHeadRight;
                        stContent = stContentRight;
                        break;
                }
                putValue(cell, dtList.Columns[col].ColumnName, 0, col, stHead);
                for (int row = 0; row < dtList.Rows.Count; row++)
                {
                    putValue(cell, dtList.Rows[row][col], row + 1, col, stContent);
                }
            }
            wb.Save(path);
            return ExportFilesPath + fileName + etsName;
        }

        //填充数据到excel中
        private static void putValue(Cells cell, object value, int row, int column, Style st)
        {       
            cell[row, column].PutValue(value);
            cell[row, column].SetStyle(st);
        }

}

//调用上面方法(MVC):
public FileResult FileExportExcel()
{
            string filePath = OperateExcel.ExportToExcel(getData(), DateTime.Now.ToString("yyyyMMddHHmmss"));
            return File(Server.MapPath(filePath), "application/ms-excel", Path.GetFileName(filePath));

}

Aspose.Cells PDF文档: http://download.csdn.net/detail/djk8888/9675095

Aspose.Cells. Demo示例库:http://download.csdn.net/detail/djk8888/9675142

本文配套源码:http://download.csdn.net/detail/djk8888/9677210

 类似资料: