/// <summary>
/// 将字符串数组写入EXCEL
/// </summary>
/// <param name="xlFile">EXCEL文件</param>
/// <param name="sheetName">EXCEL表名称</param>
/// <param name="str">输出字符串数组</param>
/// <param name="startCell">EXCEL输出起始单元格地址,如A1</param>
/// <param name="endCell">EXCEL输出结束单元格地址,如B2</param>
/// <returns>true=输出EXCEL文件成功, false=输出EXCEL文件失败</returns>
public static bool WriteExcel(string xlFile, string sheetName, string[,] str, string startCell, string endCell)
{
Excel.Application xlApp = null;
Excel.Workbook xlBook = null;
try
{
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlBook = xlApp.Workbooks.Open(xlFile, Excel.XlUpdateLinks.xlUpdateLinksNever);
Excel.Worksheet xlSheet = xlBook.Worksheets[sheetName] as Excel.Worksheet;
//Excel.Worksheet xlSheet2 = xlBook.Worksheets.Add();
//xlSheet.Copy(xlSheet2);
if (xlSheet == null)
return false;
Excel.Range rng = xlSheet.get_Range(startCell, endCell);
rng.set_Value(System.Reflection.Missing.Value, str);
xlBook.Save();
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("将字符串数组写入EXCEL出错:消息={0}, 堆栈={1}", ex.Message, ex.StackTrace));
return false;
}
finally
{
if (xlBook != null)
{
xlBook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
}
if (xlApp != null)
{
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
}
}
return true;
}
/// <summary>
/// NPOI方式创建并写EXCEL文件
/// </summary>
/// <param name="xlFile">EXCEL文件</param>
/// <param name="sheetName">EXCEL表名称</param>
/// <param name="str">输出字符串数组</param>
/// <param name="row0">输出起始行</param>
/// <param name="col0">输出起始列</param>
/// <param name="nRow">行数</param>
/// <param name="nCol">列数</param>
/// <returns>true=输出EXCEL文件成功, false=输出EXCEL文件失败</returns>
public static bool WriteNewExcel(string xlFile, string sheetName, string[,] str, int row0, int col0, int nRow, int nCol)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet(sheetName);
for (int i = 0; i < nRow - 1; i++)
{
HSSFRow row = sheet.CreateRow(row0 + i);
for (int j = 0; j < nCol - 1; j++)
{
row.CreateCell(col0 + j).SetCellValue(str[i, j]);
}
}
using (FileStream fs = new FileStream(xlFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
workbook.Write(fs);
}
return true;
}