/// <summary>
/// Excel导出写入
/// </summary>
public class ExcelHelper
{
/// <summary>
/// 当前行号【从0开始】
/// </summary>
public int rowIndex = 0;
/// <summary>
/// Excel实例
/// </summary>
private Workbook book = null;
/// <summary>
/// 当前工作表
/// </summary>
private Worksheet sheet = null;
/// <summary>
/// 返回当前sheet一共有多少列
/// </summary>
public int MaxColCount
{
get
{
return sheet.Cells.Columns.Count;
}
}
/// <summary>
/// 返回当前sheet一共有多少行
/// </summary>
public int MaxRowCount
{
get
{
return sheet.Cells.Rows.Count;
}
}
/// <summary>
/// 创建一个新的Excel
/// </summary>
public ExcelHelper()
{
book = new Workbook();
sheet = book.Worksheets[0];
}
/// <summary>
/// 创建一个新的Excel
/// </summary>
public ExcelHelper(string excelpath)
{
book = new Workbook();
book.LoadData(excelpath);
}
/// <summary>
/// 选择工作表
/// </summary>
/// <param name="index"></param>
public bool SelectWorkSheet(int index)
{
if (book.Worksheets != null && book.Worksheets.Count > index)
{
sheet = book.Worksheets[0];
return true;
}
return false;
}
/// <summary>
/// 选择工作表
/// </summary>
/// <param name="index"></param>
public bool SelectWorkSheet(string sheetName)
{
if (book.Worksheets != null && book.Worksheets[sheetName] != null)
{
sheet = book.Worksheets[sheetName];
return true;
}
return false;
}
/// <summary>
/// 添加工作薄
/// </summary>
/// <param name="sheetName">工作薄名称</param>
/// <returns></returns>
public bool AddSheet(string sheetName)
{
if (sheet.Name == "Sheet1")
{
sheet.Name = sheetName;
return true;
}
sheet = book.Worksheets.Add(sheetName);
return sheet == null;
}
/// <summary>
/// 保存
/// </summary>
/// <param name="filename"></param>
public void Save(string filename)
{
book.Save(filename);
}
/// <summary>
/// 保存
/// </summary>
/// <param name="filename"></param>
public void Save(System.IO.Stream sw)
{
book.Save(sw,FileFormatType.Excel2003);
}
/// <summary>
/// 写入数据
/// </summary>
/// <param name="colIndex">起始列号</param>
/// <param name="datas">数据数组</param>
public void WriteData(int colIndex, params string[] datas)
{
if (datas == null)
return;
foreach (string s in datas)
{
sheet.Cells[rowIndex, colIndex].PutValue(s);
colIndex++;
}
}
/// <summary>
/// 获取单元格的值
/// </summary>
public string GetCellsValue(int colIndex)
{
Cell c = sheet.Cells[rowIndex, colIndex];
if (c != null)
return c.Value.ToString();
return "";
}
}