Excel常用操作


Excel常用操作

1 讀取Excel到DataTable

 一般讀取Excel需要指定sheet名稱,當需要批量處理excel文件的時候,而且每個excel的sheet名稱又不一樣的時候,導入就成了一件惱火的事情。

先提高一個自動獲取sheet名稱的功能。

來看看代碼實現 :

復制代碼
  OleDbConnection con = new OleDbConnection(GetConn(tempxlsPath));

  DataTable dtSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

  sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString();

復制代碼

有人說:外部文件不是有效的Excel文件,沒關系,是應該office版本的文件,導致連接串有變化。

復制代碼

 

private string GetConn(string xlsPath)
{
  if (!File.Exists(xlsPath))
  {
    return "指定的Excel文件不存在!";
  }
  return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";
}

private string GetConnACE(string xlsPath)
{
  if (!File.Exists(xlsPath))
  {
    return "指定的Excel文件不存在!";
  }
  return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";
}

 

 

OleDbConnection con = new OleDbConnection(GetConn(tempxlsPath));

//讀取
try
{
  con.Open();
}
catch
{
  con.ConnectionString = GetConnACE(tempxlsPath);
  try
  {
    con.Open();
  }
  catch(Exception ex)
  {
    retmsg = ex.Message;
    return dtExcel;
  }
}

復制代碼

 

當遇到Excel不是標准的Excel時,如網頁下載的基於html格式或csv格式的文件,連接查詢就會報錯,這是就需要另存為標准的格式:

復制代碼

    Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;

    ObjWorkBook = ObjExcel.Workbooks.Open(xlsPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


    tempxlsPath = System.IO.Path.GetDirectoryName(xlsPath) + "\\" + DateTime.Now.Ticks.ToString() + ".xls";

    ((Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1]).SaveAs(tempxlsPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, false, false, false, Type.Missing, Type.Missing, true);

    ObjWorkBook.Close(false, Type.Missing, Type.Missing);
    ObjExcel.Quit();
    retmsg = KillSpecialExcel(ObjExcel);

 

 

 

  [DllImport("user32.dll", SetLastError = true)]
  static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
  private string KillSpecialExcel(Microsoft.Office.Interop.Excel.Application objExcel)
  {
    try
    {
      if (objExcel != null)
      {
        int lpdwProcessId;
        GetWindowThreadProcessId(new IntPtr(objExcel.Hwnd), out lpdwProcessId);

        System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
      }
    }
    catch (Exception ex)
    {
      return "Delete Excel Process Error:" + ex.Message;
    }
    return "";
  }

復制代碼

下面是 讀取Excel完整代碼:

復制代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Runtime.InteropServices;

namespace ExcelLib
{
/// <summary>
/// 讀取Excel文件到DataTable
/// </summary>
public class XlsRead
{
/// <summary>
/// 從Excel導入數據到DataTable
/// </summary>
/// <param name="xlsPath">xls文件路徑</param>
/// <param name="sheetName">工作區名稱,為空自動獲取第一個</param>
/// <param name="needSaveAsExcel97">是否另存為標准Excel2003-97</param>
/// <param name="delxls">是否刪除Excel文件</param>
/// <param name="retmsg">返回信息</param>
/// <returns>返回結果 DataTable</returns>
public DataTable GetDataTable(string xlsPath, string sheetName, bool needSaveAsExcel97, bool delxls, out string retmsg)
{
retmsg = "";

string tempxlsPath = xlsPath;

DataTable dtExcel = new DataTable();

if (needSaveAsExcel97)
{
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;

ObjWorkBook = ObjExcel.Workbooks.Open(xlsPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


tempxlsPath = System.IO.Path.GetDirectoryName(xlsPath) + "\\" + DateTime.Now.Ticks.ToString() + ".xls";

((Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1]).SaveAs(tempxlsPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, false, false, false, Type.Missing, Type.Missing, true);

ObjWorkBook.Close(false, Type.Missing, Type.Missing);
ObjExcel.Quit();
retmsg = KillSpecialExcel(ObjExcel);
}

OleDbConnection con = new OleDbConnection(GetConn(tempxlsPath));

//讀取
try
{
con.Open();
}
catch
{
con.ConnectionString = GetConnACE(tempxlsPath);
try
{
con.Open();
}
catch(Exception ex)
{
retmsg = ex.Message;
return dtExcel;
}
}

if (string.IsNullOrEmpty(sheetName))
{
DataTable dtSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString();

if (string.IsNullOrEmpty(sheetName))
{
retmsg = "未找到數據源";
return dtExcel;
}
}

OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [" + sheetName + "]", con);
adapter.FillSchema(dtExcel, SchemaType.Mapped);
adapter.Fill(dtExcel);
con.Close();
dtExcel.TableName = sheetName;

if (dtExcel.Rows.Count == 0)
{
retmsg = "Excel無數據";

if (needSaveAsExcel97 && File.Exists(tempxlsPath))
{
File.Delete(tempxlsPath);
}
return dtExcel;
}
else
{
if (needSaveAsExcel97 && File.Exists(tempxlsPath))
{
File.Delete(tempxlsPath);
}
if (delxls && File.Exists(xlsPath))
{
File.Delete(xlsPath);
}
}
return dtExcel;
}


private string GetConn(string xlsPath)
{
if (!File.Exists(xlsPath))
{
return "指定的Excel文件不存在!";
}
return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";

}

private string GetConnACE(string xlsPath)
{
if (!File.Exists(xlsPath))
{
return "指定的Excel文件不存在!";
}
return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";
}

[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
private string KillSpecialExcel(Microsoft.Office.Interop.Excel.Application objExcel)
{
try
{
if (objExcel != null)
{
int lpdwProcessId;
GetWindowThreadProcessId(new IntPtr(objExcel.Hwnd), out lpdwProcessId);

System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
}
catch (Exception ex)
{
return "Delete Excel Process Error:" + ex.Message;
}
return "";
}
}
}

復制代碼

以下是 Excel 批量導出的代碼,需要幾個Dll,都包含在附件中:

復制代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using org.in2bits.MyXls;
using ICSharpCode.SharpZipLib.Zip;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;

namespace ExcelLib
{
/// <summary>
/// 導出EXCEL類
/// </summary>
public class XlsExport
{
private string tempPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp" + Path.DirectorySeparatorChar;

/// <summary>
/// 構造函數,自動創建Temp文件夾
/// </summary>
public XlsExport()
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
}

private string exportname = "";

/// <summary>
/// 枚舉導出文件類型
/// </summary>
public enum FileType
{
/// <summary>
/// Excel文件
/// </summary>
xls=1,
/// <summary>
/// pdf文件
/// </summary>
pdf=2,
/// <summary>
/// txt文本文件
/// </summary>
txt=3,
/// <summary>
/// doc文檔文件
/// </summary>
doc=4,
/// <summary>
/// html網頁文件
/// </summary>
html=5
}

/// <summary>
/// 導出數據
/// </summary>
/// <param name="dt">DataTable數據集</param>
/// <param name="ftype">文件類型</param>
/// <param name="fileName">導出文件名稱 默認為時間Tick</param>
/// <returns>返回 文件路徑</returns>
public string Export(DataTable dt, FileType ftype,string fileName)
{
if (string.IsNullOrEmpty(fileName))
exportname = System.DateTime.Now.Ticks.ToString();
else
exportname = fileName;

ArrayList inputlist = new ArrayList();
ArrayList thislist = new ArrayList();
for (int i = 0; i < dt.Columns.Count; i++)
{
thislist.Add(dt.Columns[i].ColumnName);
}
inputlist.Add(thislist);

foreach (DataRow dr in dt.Rows)
{
thislist = new ArrayList();
for (int c = 0; c < dt.Columns.Count; c++)
{
thislist.Add(dr[dt.Columns[c].ColumnName].ToString());
}
inputlist.Add(thislist);
}
return Export(inputlist, ftype);
}

private string Export(ArrayList input, FileType ftype)
{
if ((int)ftype == 1)
{
return excelarraylist(input);
}
if ((int)ftype == 2)
{
return pdfarraylist(input);
}
if ((int)ftype == 3)
{
return txtarraylist(input);
}
if ((int)ftype == 4)
{
return docarraylist(input);
}
if ((int)ftype == 5)
{
return htmlarraylist(input);
}
return "";
}

private string excelarraylist(ArrayList input)//生成excel,每50000條數據生成一個xls文件,超過兩個xls則打包為zip文件,只有一個xls則直接返回xls文件
{
ArrayList filelist = new ArrayList();
string strFullPathAndName = exportname + "_0.xls";

if(File.Exists(tempPath + strFullPathAndName))
{
return "Excel文件已存在。";
}

filelist.Add(strFullPathAndName);
XlsDocument xls = new XlsDocument();
xls.FileName = tempPath + strFullPathAndName;
Worksheet sheet = xls.Workbook.Worksheets.Add(exportname);//狀態欄標題名稱
Cells cells = sheet.Cells;
int col_length = 0;
int file_i = 0;
int count_i = 0;
for (int i = 0; i < input.Count; i++)
{
if (i % 50000 == 0 && i > 0)//達到50000個,生成下一個文件
{
xls.Save();
file_i++;
count_i = 0;
strFullPathAndName = exportname + "_" + file_i + ".xls";
filelist.Add(strFullPathAndName);
xls = new XlsDocument();
xls.FileName = tempPath + strFullPathAndName;
sheet = xls.Workbook.Worksheets.Add(exportname);//狀態欄標題名稱
cells = sheet.Cells;
col_length = 0;
}
ArrayList this_list = (ArrayList)input[i];
col_length = this_list.Count;
for (int j = 0; j < this_list.Count; j++)
{
Cell cell = cells.Add(count_i + 1, j + 1, this_list[j]);
if (i == 0)
{
cell.Font.Bold = true; //字體為粗體
cell.Pattern = 1;
cell.PatternColor = Colors.Silver;
cell.TopLineStyle = 2;
cell.TopLineColor = Colors.Black;
}
if (count_i == 0)
{
cell.LeftLineStyle = 2;
cell.LeftLineColor = Colors.Black;
}
if (count_i == input.Count - 1 || count_i == 50000 - 1)
{
cell.RightLineStyle = 2;
}
else
{
cell.RightLineStyle = 1;
}
cell.RightLineColor = Colors.Black;
if (count_i == input.Count - 1 || count_i == 50000 - 1)
{
cell.BottomLineStyle = 2;
cell.BottomLineColor = Colors.Black;
}
}
count_i++;
}
xls.Save();
if (filelist.Count == 1)//只有一個xls文件,直接返回xls文件
{
return tempPath + strFullPathAndName;
}
else//超過一個xls文件,打包生成zip文件
{
MemoryStream ms = null;
ms = new MemoryStream();
ZipOutputStream zos = new ZipOutputStream(ms);
string folder_name = DateTime.Now.Ticks.ToString();
string filename = exportname + ".zip";
FileStream fileStreamOut = new FileStream(tempPath + filename, FileMode.Create, FileAccess.Write);
ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut);
byte[] buffer = new byte[32];
for (int i = 0; i < filelist.Count; i++)
{
string SrcFile = tempPath + filelist[i].ToString();
FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile));
zipOutStream.PutNextEntry(entry);
int size;
do
{
size = fileStreamIn.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
fileStreamIn.Close();
}
zos.Finish();
zos.Close();
zipOutStream.Close();
fileStreamOut.Close();
for (int i = 0; i < filelist.Count; i++)
{
File.Delete(tempPath + filelist[i].ToString());
}

return tempPath + filename;
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.Clear();//清除緩沖區所有內容
//HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
//HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + filename));
//HttpContext.Current.Response.Flush();
//File.Delete(HttpContext.Current.Server.MapPath("tmp/" + filename));
//HttpContext.Current.Response.End();
}
}
private string pdfarraylist(ArrayList input)
{
if (!File.Exists(tempPath + "msyh.ttf"))
{
if (!File.Exists(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "msyh.ttf"))
return "導入失敗,msyh.ttf文件不存在,將文件放於Temp目錄下后重試!";
else
File.Copy(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "msyh.ttf", tempPath + "msyh.ttf");
}
try
{
string strFullPathAndName = exportname + ".pdf";
if (File.Exists(tempPath + strFullPathAndName))
{
return "pdf文件已存在。";
}
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(tempPath + strFullPathAndName, FileMode.Create));
document.Open();
BaseFont titleChinese = BaseFont.CreateFont(tempPath+"msyh.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
BaseFont commonChinese = BaseFont.CreateFont(tempPath + "msyh.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.Font tChinese = new iTextSharp.text.Font(titleChinese, 12);
iTextSharp.text.Font cChinese = new iTextSharp.text.Font(commonChinese, 10);
document.Add(new Paragraph(exportname, tChinese));
//iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("xxx.jpg"));
//document.Add(jpeg);
int colnum = 1;
ArrayList thislist = (ArrayList)input[0];
colnum = thislist.Count;
PdfPTable table = new PdfPTable(colnum);
for (int i = 0; i < input.Count; i++)
{
thislist = (ArrayList)input[i];
iTextSharp.text.Font thisfont = cChinese;
if (i == 0)
{
thisfont = tChinese;
}
for (int j = 0; j < thislist.Count; j++)
{
Phrase this_phrase = new Phrase(thislist[j].ToString(), thisfont);
iTextSharp.text.pdf.PdfPCell cell = new PdfPCell(this_phrase);
if (i == 0)
{
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.BackgroundColor = BaseColor.GRAY;
}
table.AddCell(cell);
}
}
document.Add(table);
document.Close();

return tempPath + strFullPathAndName;
}
catch (Exception ex)
{
return "導入失敗:" + ex.Message;
}
}

private string txtarraylist(ArrayList input)
{
string strFullPathAndName = exportname + ".txt";
if (File.Exists(tempPath + strFullPathAndName))
{
return "txt文件已存在。";
}
StreamWriter writer = new StreamWriter(tempPath + strFullPathAndName, false, Encoding.UTF8);
for (int i = 0; i < input.Count; i++)
{
ArrayList thislist = (ArrayList)input[i];
string thisline = "";
for (int j = 0; j < thislist.Count; j++)
{
if (thisline != "")
{
thisline += '\t';
}
thisline += thislist[j].ToString();
}
writer.WriteLine(thisline);
}
writer.Close();

return tempPath + strFullPathAndName;

//string filename = HttpUtility.UrlEncode(exportname + ".txt", Encoding.UTF8);
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.Clear();//清除緩沖區所有內容
//HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
//HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
//HttpContext.Current.Response.Flush();
//File.Delete(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
//HttpContext.Current.Response.End();
}

private string docarraylist(ArrayList input)
{
string strFullPathAndName = exportname + ".doc";
if (File.Exists(tempPath + strFullPathAndName))
{
return "doc文件已存在。";
}
StreamWriter writer = new StreamWriter(tempPath + strFullPathAndName, false, Encoding.UTF8);
writer.WriteLine("<html>");
writer.WriteLine("<body style='font-size:12px'>");
writer.WriteLine("<table border='2' width='100%'>");
for (int i = 0; i < input.Count; i++)
{
ArrayList thislist = (ArrayList)input[i];
writer.WriteLine("<tr>");
for (int j = 0; j < thislist.Count; j++)
{
if (i == 0)
{
writer.WriteLine("<th>" + thislist[j].ToString() + "</th>");
}
else
{
writer.WriteLine("<td>" + thislist[j].ToString() + "</td>");
}

}
writer.WriteLine("</tr>");
}
writer.WriteLine("</table>");
writer.WriteLine("</body>");
writer.WriteLine("</html>");
writer.Close();
return tempPath + strFullPathAndName;

//string filename = HttpUtility.UrlEncode(exportname + ".doc", Encoding.UTF8);
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.Clear();//清除緩沖區所有內容
//HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
//HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
//HttpContext.Current.Response.Flush();
//File.Delete(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
//HttpContext.Current.Response.End();
}

private string htmlarraylist(ArrayList input)
{
string strFullPathAndName = exportname + ".html";
if (File.Exists(tempPath + strFullPathAndName))
{
return "html文件已存在。";
}
StreamWriter writer = new StreamWriter(tempPath + strFullPathAndName, false, Encoding.UTF8);
writer.WriteLine("<html>");
writer.WriteLine("<body style='font-size:12px'>");
writer.WriteLine("<table border='2' width='100%'>");
for (int i = 0; i < input.Count; i++)
{
ArrayList thislist = (ArrayList)input[i];
writer.WriteLine("<tr>");
for (int j = 0; j < thislist.Count; j++)
{
if (i == 0)
{
writer.WriteLine("<th>" + thislist[j].ToString() + "</th>");
}
else
{
writer.WriteLine("<td>" + thislist[j].ToString() + "</td>");
}

}
writer.WriteLine("</tr>");
}
writer.WriteLine("</table>");
writer.WriteLine("</body>");
writer.WriteLine("</html>");
writer.Close();
return tempPath + strFullPathAndName;
//string filename = HttpUtility.UrlEncode(exportname + ".html", Encoding.UTF8);
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.Clear();//清除緩沖區所有內容
//HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
//HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
//HttpContext.Current.Response.Flush();
//File.Delete(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
//HttpContext.Current.Response.End();
}
}
}

復制代碼

 

加個附件真麻煩,不過還是加上了。

ExcelLib.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM