using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web.UI;
namespace WX_Card.CardUtility
{
public class FileHelper
{
public DataSet ExcelToDS(string Path)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = null;
try
{
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
if (strTableNames.Count() > 0)
{
OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", strTableNames[0]), conn);
ds = new DataSet();
odda.Fill(ds, strTableNames[0]);
}
}
catch
{
}
finally
{
conn.Close();
}
return ds;
}
public DataSet ExcelToDSNew(string Path, bool hasheader = false)
{
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";" + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = null;
try
{
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
if (strTableNames.Count() > 0)
{
OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", strTableNames[0]), conn);
ds = new DataSet();
odda.Fill(ds, strTableNames[0]);
}
if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
string columnname = "F" + (i + 1).ToString();
if (ds.Tables[0].Columns[i].ColumnName.Equals(columnname))
{
ds.Tables[0].Columns[i].ColumnName = ds.Tables[0].Rows[0][columnname].ToString();
}
}
ds.Tables[0].Rows.RemoveAt(0);
}
}
catch
{
}
finally
{
conn.Close();
}
return ds;
}
public DataSet ExcelToD_Data(string Path, bool hasheader = false)
{
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";" + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = null;
try
{
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
if (strTableNames.Count() > 0)
{
OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", strTableNames[1]), conn);
ds = new DataSet();
odda.Fill(ds, strTableNames[1]);
}
if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
string columnname = "F" + (i + 1).ToString();
if (ds.Tables[0].Columns[i].ColumnName.Equals(columnname))
{
ds.Tables[0].Columns[i].ColumnName = ds.Tables[0].Rows[0][columnname].ToString();
}
}
ds.Tables[0].Rows.RemoveAt(0);
}
}
catch
{
}
finally
{
conn.Close();
}
return ds;
}
public DataTable CSVToTable(string filePath)
{
Encoding encoding = Encoding.Default;
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
string openid = string.Empty;
try
{
string strLine = "";
string[] aryLine = null;
string[] tableHead = null;
int columnCount = 0;
bool IsFirst = true;
while ((strLine = sr.ReadLine()) != null)
{
if (IsFirst == true)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length;
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
if (!dt.Columns.Contains(dc.ToString()))
{
dt.Columns.Add(dc);
}
else
{
throw new Exception("列名出现重复:" + dc.ToString());
}
}
}
else
{
try
{
columnCount = dt.Columns.Count;
aryLine = strLine.Split(',');
if (string.IsNullOrWhiteSpace(aryLine[0]))
{
continue;
}
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j].Replace("\"", "").Replace("\t", "");
}
dt.Rows.Add(dr);
}
catch(Exception ex)
{
}
}
}
if (aryLine != null && aryLine.Length > 0)
{
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
sr.Close();
fs.Close();
}
return dt;
}
public void DSToExcel(string Path, DataSet oldds)
{
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + Path + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = "select * from [Sheet1$]";
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
System.Data.OleDb.OleDbCommandBuilder builder = new OleDbCommandBuilder(myCommand);
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
DataSet newds = new DataSet();
myCommand.Fill(newds, "Table1");
for (int i = 0; i < oldds.Tables[0].Rows.Count; i++)
{
DataRow nrow = oldds.Tables["Table1"].NewRow();
for (int j = 0; j < newds.Tables[0].Columns.Count; j++)
{
nrow[j] = oldds.Tables[0].Rows[i][j];
}
newds.Tables["Table1"].Rows.Add(nrow);
}
myCommand.Update(newds, "Table1");
myConn.Close();
}
public bool DsSaveToExcel(string path, DataTable dt)
{
bool result = false;
try
{
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
using (OleDbConnection ole_conn = new OleDbConnection(sConnectionString))
{
ole_conn.Open();
using (OleDbCommand ole_cmd = ole_conn.CreateCommand())
{
try
{
ole_cmd.CommandText = "CREATE TABLE 中心铺货 ([配送中心ID] Int,[门店ID] Int,[货品ID] Int,[数量] Int)";
ole_cmd.ExecuteNonQuery();
for (int i = 0; i < dt.Rows.Count; i++)
{
ole_cmd.CommandText = string.Format("insert into 中心铺货([配送中心ID],[门店ID],[货品ID],[数量])values(4450,19176,{0},{1})", dt.Rows[i]["货品ID"].ToString(), dt.Rows[i]["数量"].ToString());
ole_cmd.ExecuteNonQuery();
}
}
catch { }
result = true;
}
ole_conn.Close();
}
}
catch { }
return result;
}
public bool DsSaveToExcelForJD(string path, DataTable dt)
{
bool result = false;
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
using (OleDbConnection ole_conn = new OleDbConnection(sConnectionString))
{
ole_conn.Open();
using (OleDbCommand ole_cmd = ole_conn.CreateCommand())
{
try
{
ole_cmd.CommandText = "CREATE TABLE 商品图列表 ([地址] varchar(200),[京东编码] varchar(100),[商家编码] varchar(100))";
ole_cmd.ExecuteNonQuery();
for (int i = 0; i < dt.Rows.Count; i++)
{
ole_cmd.CommandText = string.Format("insert into 商品图列表([地址],[京东编码],[商家编码])values('{0}','{1}','{2}')", dt.Rows[i]["地址"].ToString(), dt.Rows[i]["京东编码"].ToString(), dt.Rows[i]["商家编码"].ToString());
ole_cmd.ExecuteNonQuery();
}
}
catch { }
result = true;
}
ole_conn.Close();
}
return result;
}
public void SaveAsXlS(string fileName, DataTable dataTable)
{
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
DataSet set = new DataSet();
dataTable.TableName = fileName;
set.Tables.Add(dataTable.Copy());
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = set;
grid.DataMember = set.Tables[dataTable.TableName].TableName;
grid.DataBind();
using (StreamWriter sw = new StreamWriter(fileName))
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}
}
public static void SaveCSV(DataTable dt, string fullPath)
{
FileInfo fi = new FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n'))
{
str = string.Format("\"{0}\"", str);
}
data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
public static void downloadImage(string Imgurl, string pathname, string filename)
{
WebRequest request = WebRequest.Create(Imgurl);
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
if (!System.IO.Directory.Exists(pathname))
{
System.IO.Directory.CreateDirectory(pathname);
}
FileStream writer = new FileStream(pathname + filename, FileMode.OpenOrCreate, FileAccess.Write);
byte[] buff = new byte[512];
int c = 0;
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
response.Close();
}
public static void downloadImage(string Imgurl, Dictionary<string, string> keyValues)
{
foreach (var item in keyValues)
{
try
{
Thread.Sleep(2);
WebRequest request = WebRequest.Create(Imgurl);
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
if (!Directory.Exists(item.Value))
{
Directory.CreateDirectory(item.Value);
}
FileStream writer = new FileStream(item.Value + item.Key, FileMode.OpenOrCreate, FileAccess.Write);
byte[] buff = new byte[512];
int c = 0;
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
response.Close();
}
catch (Exception ex)
{
Console.WriteLine("***************保存图片报错了,错误{0}****************", ex.Message);
}
}
}
public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
{
FileInfo firstFileInfo = new FileInfo(sFile);
if (sfsc == true && firstFileInfo.Length < size * 1024)
{
firstFileInfo.CopyTo(dFile);
return true;
}
System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
int sW = 0, sH = 0;
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);
FileInfo fi = new FileInfo(dFile);
if (fi.Length > 1024 * size)
{
flag = flag - 10;
CompressImage(sFile, dFile, flag, size, false);
}
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
public static void DeleteDirectory(string directoryPath, string fileName)
{
for (int i = 0; i < Directory.GetFiles(directoryPath).ToList().Count; i++)
{
if (Directory.GetFiles(directoryPath)[i] == fileName)
{
File.Delete(fileName);
}
}
for (int i = 0; i < Directory.GetDirectories(directoryPath).ToList().Count; i++)
{
if (Directory.GetDirectories(directoryPath)[i] == fileName)
{
Directory.Delete(fileName, true);
}
}
}
public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
{
int newheigth = heigth;
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFileLocation);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
if (keepAspectRatio || getCenter)
{
int bmpY = 0;
double resize = (double)FullsizeImage.Width / (double)width;
if (getCenter)
{
bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);
Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize)));
Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);
FullsizeImage.Dispose();
using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
{
Graphics cutImg = Graphics.FromImage(tempImg);
cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);
FullsizeImage = tempImg;
orImg.Dispose();
cutImg.Dispose();
return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
}
}
else newheigth = (int)(FullsizeImage.Height / resize);
}
return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
}
public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width)
{
return resizeImageFromFile(OriginalFileLocation, heigth, width, false, false);
}
public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio)
{
return resizeImageFromFile(OriginalFileLocation, heigth, width, keepAspectRatio, false);
}
public bool NewExport(List<DictionaryEntry> list, string filepath,out string ErrorMsg)
{
bool bSuccess = true;
ErrorMsg = string.Empty;
Microsoft.Office.Interop.Excel.Application appexcel = new Microsoft.Office.Interop.Excel.Application();
System.Reflection.Missing miss = System.Reflection.Missing.Value;
appexcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbookdata = null;
Microsoft.Office.Interop.Excel.Worksheet worksheetdata = null;
Microsoft.Office.Interop.Excel.Range rangedata;
workbookdata = appexcel.Workbooks.Add();
appexcel.Visible = false;
appexcel.DisplayAlerts = false;
try
{
foreach (var lv in list)
{
var keys = lv.Key as List<string>;
var values = lv.Value as List<IList<object>>;
worksheetdata = (Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets.Add(miss, workbookdata.ActiveSheet);
for (int i = 0; i < keys.Count - 1; i++)
{
worksheetdata.Name = keys[0];
worksheetdata.Cells[1, i + 1] = keys[i + 1];
}
rangedata = worksheetdata.get_Range("a2", miss);
Microsoft.Office.Interop.Excel.Range xlrang = null;
int irowcount = values.Count;
int iparstedrow = 0, icurrsize = 0;
int ieachsize = 10000;
int icolumnaccount = keys.Count - 1;
object[,] objval = new object[ieachsize, icolumnaccount];
icurrsize = ieachsize;
while (iparstedrow < irowcount)
{
if ((irowcount - iparstedrow) < ieachsize)
icurrsize = irowcount - iparstedrow;
for (int i = 0; i < icurrsize; i++)
{
for (int j = 0; j < icolumnaccount; j++)
{
var v = values[i + iparstedrow][j];
objval[i, j] = v != null ? v.ToString() : "";
}
}
string X = "A" + ((int)(iparstedrow + 2)).ToString();
string col = "";
if (icolumnaccount <= 26)
{
col = ((char)('A' + icolumnaccount - 1)).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString();
}
else
{
col = ((char)('A' + (icolumnaccount / 26 - 1))).ToString() + ((char)('A' + (icolumnaccount % 26 - 1))).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString();
}
xlrang = worksheetdata.get_Range(X, col);
xlrang.NumberFormat = "@";
xlrang.Value2 = objval;
iparstedrow = iparstedrow + icurrsize;
}
}
((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet1"]).Delete();
((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet2"]).Delete();
((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet3"]).Delete();
workbookdata.SaveAs(filepath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
workbookdata.Close(false, miss, miss);
appexcel.Workbooks.Close();
appexcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbookdata);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel.Workbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel);
GC.Collect();
}
catch (Exception ex)
{
ErrorMsg = ex.Message;
bSuccess = false;
}
finally
{
if (appexcel != null)
{
}
}
return bSuccess;
}
public static bool ExportToExcel(DataTable table, string saveFileName,string columnNames)
{
bool fileSaved = false;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return fileSaved;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
long rows = table.Rows.Count;
string[] columnNameList = new string[] { };
List<int> numberFormat = new List<int>();
int diyNameCount = 0;
if (!string.IsNullOrWhiteSpace(columnNames)) {
columnNameList = columnNames.Split(',');
diyNameCount = columnNameList.Count();
}
if (rows > 65535)
{
long pageRows = 60000;
int scount = (int)(rows / pageRows);
if (scount * pageRows < table.Rows.Count)
{
scount = scount + 1;
}
for (int sc = 1; sc <= scount; sc++)
{
if (sc > 1)
{
object missing = System.Reflection.Missing.Value;
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(
missing, missing, missing, missing);
}
else
{
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[sc];
}
string[,] datas = new string[pageRows + 1, table.Columns.Count + 1];
for (int i = 0; i < table.Columns.Count; i++)
{
if(i < diyNameCount)
{
string headerName = columnNameList[i];
if (headerName.EndsWith("numberformat"))
{
numberFormat.Add(i);
datas[0, i] = headerName.Replace("numberformat","");
}
}
else
{
datas[0, i] = table.Columns[i].Caption;
}
}
Microsoft.Office.Interop.Excel.Range range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
range.Font.Size = 9;
int init = int.Parse(((sc - 1) * pageRows).ToString());
int r = 0;
int index = 0;
int result;
if (pageRows * sc >= table.Rows.Count)
{
result = table.Rows.Count;
}
else
{
result = int.Parse((pageRows * sc).ToString());
}
for (r = init; r < result; r++)
{
index = index + 1;
for (int i = 0; i < table.Columns.Count; i++)
{
if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal)
|| table.Columns[i].DataType == typeof(Double) || table.Columns[i].DataType == typeof(Int64)
|| table.Columns[i].DataType == typeof(DateTime))
{
object obj = table.Rows[r][table.Columns[i].ColumnName];
if (numberFormat.Contains(i))
{
datas[index, i] = obj == null ? "" : "'" + obj.ToString().Trim();
}
else
{
datas[index, i] = obj == null ? "" : obj.ToString().Trim();
}
}
}
}
Microsoft.Office.Interop.Excel.Range fchR = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[index + 2, table.Columns.Count + 1]];
fchR.Value2 = datas;
worksheet.Columns.EntireColumn.AutoFit();
range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[index + 1, table.Columns.Count]];
range.Font.Size = 9;
range.RowHeight = 14.25;
range.Borders.LineStyle = 1;
range.HorizontalAlignment = 1;
}
}
else
{
string[,] datas = new string[table.Rows.Count + 2, table.Columns.Count + 1];
for (int i = 0; i < table.Columns.Count; i++)
{
if (i < diyNameCount)
{
string headerName = columnNameList[i];
if (headerName.EndsWith("numberformat"))
{
numberFormat.Add(i);
}
datas[0, i] = headerName.Replace("numberformat", "");
}
else
{
datas[0, i] = table.Columns[i].Caption;
}
}
Microsoft.Office.Interop.Excel.Range range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
range.Font.Size = 9;
int r = 0;
for (r = 0; r < table.Rows.Count; r++)
{
for (int i = 0; i < table.Columns.Count; i++)
{
if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal)
|| table.Columns[i].DataType == typeof(Double) || table.Columns[i].DataType == typeof(Int64)
|| table.Columns[i].DataType == typeof(DateTime))
{
object obj = table.Rows[r][table.Columns[i].ColumnName];
if(numberFormat.Contains(i))
{
datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();
}
else
{
datas[r + 1, i] = obj == null ? "" : obj.ToString().Trim();
}
}
}
}
Microsoft.Office.Interop.Excel.Range fchR = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 1]];
fchR.Value2 = datas;
worksheet.Columns.EntireColumn.AutoFit();
range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1, table.Columns.Count]];
range.Font.Size = 9;
range.RowHeight = 14.25;
range.Borders.LineStyle = 1;
range.HorizontalAlignment = 1;
}
if (saveFileName != "")
{
try
{
workbook.Saved = true;
string dir = System.AppDomain.CurrentDomain.BaseDirectory + "outfile\\";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
workbook.SaveCopyAs(dir + saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();
return fileSaved;
}
}
}
public class ExcelHelper : IDisposable
{
private string fileName = null;
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
}
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf( ".xlsx") > 0)
workbook = new XSSFWorkbook();
else if (fileName.IndexOf( ".xls") > 0)
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true)
{
IRow row = sheet.CreateRow( 0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs);
return count;
}
catch (Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return -1;
}
}
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf( ".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf( ".xls") > 0)
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null)
{
sheet = workbook.GetSheetAt( 0);
}
}
else
{
sheet = workbook.GetSheetAt( 0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow( 0);
int cellCount = firstRow.LastCellNum;
if (isFirstRowColumn)
{
for ( int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
int rowCount = sheet.LastRowNum;
for ( int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
DataRow dataRow = data.NewRow();
for ( int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return null;
}
}
public void Dispose()
{
Dispose( true);
GC.SuppressFinalize( this);
}
protected virtual void Dispose(bool disposing)
{
if (! this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
}
fs = null;
disposed = true;
}
}
}
}