Import and export using Aspose. Cells
- 2021-11-02 00:27:24
- OfStack
This article example for everyone to share Aspose. Cells implementation of import and export of the specific code, for your reference, the specific content is as follows
This is a self-organized import and export class, which has comments.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
namespace Lzd.Mvc.EasyUi.Common.ExcelUtil
{
///
/// excel Operation base class
///
///
public class BaseExcelUtil
{
private Workbook m_Wb = null;
///
/// Generate Excel
///
/// Template Excel Path of + Filename
/// Excel Byte object of file
public byte[] CreateExcel(string url)
{
FileStream fs = null;
try
{
// Read template Excel The contents of the file
fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.Read);
m_Wb = new Workbook();
m_Wb.Open(fs);
setValue(m_Wb);
// Converts to a byte object and returns
return m_Wb.SaveToStream().ToArray();
}
catch (Exception ex)
{
throw ex;
}
finally
{
fs.Close();
}
}
///
/// Setting Excel Data in
/// The data source is datable Type
///
/// Workbook
public virtual void setValue(Workbook wb)
{
throw new Exception("The method or operation is not implemented.");
}
///
/// Read Excel
///
/// Excel Path of + Filename
/// Excel Byte object of file
public DataTable GetExcel(string url)
{
FileStream fs = null;
try
{
// Read Excel The contents of the file
fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.Read);
m_Wb = new Workbook();
m_Wb.Open(fs);
// Setting Excel Data in
return getValue(m_Wb);
}
finally
{
fs.Close();
}
}
///
/// Acquire Excel Data in
///
/// Workbook
public virtual DataTable getValue(Workbook wb)
{
throw new Exception("The method or operation is not implemented.");
}
///
/// Set string value
///
///
///
public void putValue(Cell c, object value)
{
try
{
if (value == null || object.Equals(value, DBNull.Value) || value.ToString().Trim().Length == 0)
{
}
else
{
c.PutValue(value.ToString());
}
}
catch (Exception)
{
c.PutValue("--");
}
}
///
/// Set numeric values
///
///
///
public void putValueDouble(Cell c, object value)
{
try
{
if (value == null || object.Equals(value, DBNull.Value) || value.ToString().Trim().Length == 0)
{
}
else
{
c.PutValue(Decimal.Parse(value.ToString()));
}
}
catch (Exception)
{
c.PutValue(value.ToString());
}
}
///
/// Set date value
///
///
///
public void putDateValue(Cell c, object value)
{
try
{
if (value == null || object.Equals(value, DBNull.Value) || value.ToString().Trim().Length == 0)
{
}
else
{
c.PutValue(DateTime.Parse(value.ToString()));
}
}
catch (Exception)
{
c.PutValue(value.ToString());
}
}
}
}
////Implement the base class
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
namespace Lzd.Mvc.EasyUi.Common.ExcelUtil
{
///
/// Excel Help class
///
public class ExcelUtil :BaseExcelUtil
{
private DataTable dt;
private string title;
public ExcelUtil() {
}
///
/// What line does the read start from
///
public int FirstRow { get; set; }
///
/// What column does the read start from
///
public int FirstColumns { get; set; }
///
/// excel Title
///
public string Title
{
get { return title; }
set { title = value; }
}
private string fileName;
///
/// Filename
///
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
public bool Flag
{
set;
get;
}
///
///
/// Derived set value
public override void setValue(Workbook wb)
{
int index = 0;
Worksheet ws = null;
int rcount = dt.Rows.Count, columns = dt.Columns.Count;
if (dt != null && dt.Rows.Count > 0)
{
index = wb.Worksheets.AddCopy(0);
ws = wb.Worksheets[index];
ws.Name = FileName.Replace(".xls", "");
try
{
putValue(ws.Cells[0, 0], this.title);
int i = 1;
for (int j = 0; j < columns; j++)
{
putValue(ws.Cells[1, j], dt.Columns[j].ColumnName);
}
for (int j = 0; j < rcount; j++)
{
i++;
for (int h = 0; h < columns; h++)
{
putValue(ws.Cells[i, h], dt.Rows[j][h].ToString());
}
}
wb.Worksheets.RemoveAt(0);
}
catch (Exception ex)
{
throw ex;
}
}
}
///
/// Import excel
///
/// File name read
/// What line does the read start from
/// What column does the read start from
///
///
public override DataTable getValue(Workbook wb)
{
Worksheet sheet = wb.Worksheets[0];
Cells cells = sheet.Cells;
return cells.ExportDataTableAsString(FirstRow, FirstColumns, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
}
}
}
/////Export call method
public ActionResult ToExcel() {
List list = new List();
for (int i = 0; i < 100; i++)
{
UserInfo info = new UserInfo();
info.Age = i.ToString();
info.ID = i;
info.Name = " Name " + i;
list.Add(info);
}
/// Will list Type conversion to datatable
DataTable dt= DataTableHelper.IListToDataTable(list);
// Instantiate a helper class
ExcelUtil exc = new ExcelUtil();
exc.Dt = dt;
exc.FileName = " Export test .xls";
exc.Title = " Export test ";
// Templates to be written to
string url = Server.MapPath("/Content/Down/template.xls");
byte[] data = exc.CreateExcel(url);
// Browser downloads files
Response.AppendHeader("Content-Disposition", "attachment; filename=" + exc.FileName);//HttpUtility.UrlEncode(r.FileName, Encoding.UTF8));
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Length", data.Length.ToString());
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.BinaryWrite(data);
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
return Content("ss");
}
///Import call method
public ActionResult ImportExcel()
{
string url = Server.MapPath("/Content/Down/Import.xls");
ExcelUtil exc = new ExcelUtil();
exc.FirstRow = 1;
exc.FirstColumns = 0;
DataTable dt= exc.GetExcel(url);
return Content("ss");
}