using System;
using System.Collections.Generic;
using
System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
namespace Reuters.ProcessQuality.ContentAuto.Lib
{
public class
XlsOrCsvUtil
{
/// <summary>
/// Generate Xls
Or Csv File
/// </summary>
/// <param
name="path">file path name need to save </param>
///
<param name="dicList">title and body</param>
///
<returns></returns>
public static bool
GenerateXls0rCsv(string path, Dictionary<string, List<string>>
dicList)
{
if (dicList == null || dicList.Count <=
1)//title must exist while no data in file
{
string msg = string.Format("no data need to generate");
//logger.Log(msg, Logger.LogType.LogType_Error);
throw new
Exception(msg);
//return false;
}
using (ExcelApp app = new ExcelApp(false, false))
{
try
{
Workbook
wBook = ExcelUtil.CreateOrOpenExcelFile(app, path);
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
FillExcel(wSheet, dicList);
app.ExcelAppInstance.AlertBeforeOverwriting = false;
wBook.Save();
//TaskResultList.Add(new
TaskResultEntry(MethodBase.GetCurrentMethod().DeclaringType.FullName.Replace("Ric.Generator.Lib.",
""), "ResultFile", path));
return true;
}
catch (Exception ex)
{
string msg = string.Format("generate XlsOrCsv file error ,msg:{0}",
ex.ToString());
//logger.Log(msg,
Logger.LogType.LogType_Error);
throw new
Exception(msg);
//return false;
}
}
}
private static void FillExcel(Worksheet wSheet, Dictionary<string,
List<string>> dic)
{
int rowCount =
dic.Count;
SetTitle(wSheet, dic.Values.ToList()[0]);
for (int i = 1; i < rowCount; i++)
{
var list = dic.Values.ToList()[i];
for (int j = 0; j < list.Count; j++)
{
((Range)wSheet.Cells[i + 1, j + 1]).NumberFormatLocal =
"@";
wSheet.Cells[i + 1, j + 1] = list[j];
}
}
}
private static void SetTitle(Worksheet wSheet, List<string>
list)
{
for (int i = 0; i < list.Count; i++)
{
((Range)wSheet.Columns[ToName(i),
System.Type.Missing]).ColumnWidth = 20;
wSheet.Cells[1, i +
1] = list[i];
}
//((Range)wSheet.Columns["A:" + ToName(list.Count - 1),
System.Type.Missing]).Font.Name = "Arail";//set style of XlsOrCsv
//((Range)wSheet.Rows[1, Type.Missing]).Font.Bold =
System.Drawing.FontStyle.Bold;
//((Range)wSheet.Rows[1,
Type.Missing]).Font.Color =
System.Drawing.ColorTranslator.ToOle(Color.Black);
}
public static string ToName(int index)
{
if
(index < 0)
throw new Exception("invalid parameter");
List<string> chars = new List<string>();
do
{
if (chars.Count > 0)
index--;
chars.Insert(0, ((char)(index % 26 + (int)‘A‘)).ToString());
index = (int)((index - index % 26) / 26);
}
while (index > 0);
return String.Join(string.Empty, chars.ToArray());
}
}
}
a helper class for generating xls or csv file,布布扣,bubuko.com