C# 读取EXCEL文件的三种经典方法

C# 读取EXCEL文件的三种经典方法,第1张

using System;

using SystemData;using SystemConfiguration;

using SystemWeb;

using MicrosoftOfficeInterop;

using MicrosoftOfficeCore;

namespace MicrosoftOfficeInteropExcelEdit{    

////// MicrosoftOfficeInteropExcelEdit 的摘要说明

public class ExcelEdit   

 {    

    public string mFilename;    

    public MicrosoftOfficeInteropExcelApplication app;     

   public MicrosoftOfficeInteropExcelWorkbooks wbs;    

    public MicrosoftOfficeInteropExcelWorkbook wb;    

    public MicrosoftOfficeInteropExcelWorksheets wss;     

   public MicrosoftOfficeInteropExcelWorksheet ws;     

   public ExcelEdit()        

{            //            // TODO: 在此处添加构造函数逻辑            //        }    

    public void Create()//创建一个MicrosoftOfficeInteropExcel对象    

    {            

     app = new MicrosoftOfficeInteropExcelApplication();      

      wbs = appWorkbooks;       

     wb = wbsAdd(true);     

   }      

  public void Open(string FileName)//打开一个MicrosoftOfficeInteropExcel文件       

 {            

app = new MicrosoftOfficeInteropExcelApplication();           

 wbs = appWorkbooks;            

wb = wbsAdd(FileName);            

//wb = wbsOpen(FileName, 0, true, 5,"", "", true, MicrosoftOfficeInteropExcelXlPlatformxlWindows, "t", false, false, 0, true,TypeMissing,TypeMissing);           

 //wb = wbsOpen(FileName,TypeMissing,TypeMissing,TypeMissing,TypeMissing,TypeMissing,TypeMissing,MicrosoftOfficeInteropExcelXlPlatformxlWindows,TypeMissing,TypeMissing,TypeMissing,TypeMissing,TypeMissing,TypeMissing,TypeMissing);            

mFilename = FileName;       

 }        

public MicrosoftOfficeInteropExcelWorksheet GetSheet(string SheetName)        //获取一个工作表      

  {            

MicrosoftOfficeInteropExcelWorksheet s = (MicrosoftOfficeInteropExcelWorksheet)wbWorksheets[SheetName];           

 return s;    

    }     

   public MicrosoftOfficeInteropExcelWorksheet AddSheet(string SheetName)        //添加一个工作表        

{          

  MicrosoftOfficeInteropExcelWorksheet s = (MicrosoftOfficeInteropExcelWorksheet)wbWorksheetsAdd(TypeMissing, TypeMissing, TypeMissing, TypeMissing);           

 sName = SheetName;            

return s;       

 }       

 public void DelSheet(string SheetName)//删除一个工作表      

  {        

    ((MicrosoftOfficeInteropExcelWorksheet)wbWorksheets[SheetName])Delete();  

      }        

public MicrosoftOfficeInteropExcelWorksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一     

   {            

MicrosoftOfficeInteropExcelWorksheet s = (MicrosoftOfficeInteropExcelWorksheet)wbWorksheets[OldSheetName];        

    sName = NewSheetName;         

   return s;       

 }        

public MicrosoftOfficeInteropExcelWorksheet ReNameSheet(MicrosoftOfficeInteropExcelWorksheet Sheet, string NewSheetName)//重命名一个工作表二       

 {            

SheetName = NewSheetName;            

return Sheet;        

}       

 public void SetCellValue(MicrosoftOfficeInteropExcelWorksheet ws, int x, int y, object value)        //ws:要设值的工作表    X行Y列    value  值       

 {           

 wsCells[x, y] = value;     

   }        

public void SetCellValue(string ws, int x, int y, object value)        //ws:要设值的工作表的名称 X行Y列 value 值      

  {            

GetSheet(ws)Cells[x, y] = value;      

  }        

public void SetCellProperty(MicrosoftOfficeInteropExcelWorksheet ws, int Startx, int Starty, int Endx, int Endy, int size, string name, MicrosoftOfficeInteropExcelConstants color, MicrosoftOfficeInteropExcelConstants HorizontalAlignment)        //设置一个单元格的属性  字体,  大小,颜色  ,对齐方式      

  {            

name = "宋体";           

 size = 12;            

color = MicrosoftOfficeInteropExcelConstantsxlAutomatic;           

 HorizontalAlignment = MicrosoftOfficeInteropExcelConstantsxlRight;    

 wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])FontName = name;            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])FontSize = size;            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])FontColor = color;            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])HorizontalAlignment = HorizontalAlignment;        

}       

 public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, MicrosoftOfficeInteropExcelConstants color, MicrosoftOfficeInteropExcelConstants HorizontalAlignment)        

{           

 //name = "宋体";           

 //size = 12;           

 //color = MicrosoftOfficeInteropExcelConstantsxlAutomatic;          

  //HorizontalAlignment = MicrosoftOfficeInteropExcelConstantsxlRight;            MicrosoftOfficeInteropExcelWorksheet ws = GetSheet(wsn);            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])FontName = name;            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])FontSize = size;            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])FontColor = color;            wsget_Range(wsCells[Startx, Starty], wsCells[Endx, Endy])HorizontalAlignment = HorizontalAlignment;       

 }      

  public void UniteCells(MicrosoftOfficeInteropExcelWorksheet ws, int x1, int y1, int x2, int y2)        //合并单元格     

   {            

wsget_Range(wsCells[x1, y1], wsCells[x2, y2])Merge(TypeMissing);    

    }        

public void UniteCells(string ws, int x1, int y1, int x2, int y2)        //合并单元格       

 {            

GetSheet(ws)get_Range(GetSheet(ws)Cells[x1, y1], GetSheet(ws)Cells[x2, y2])Merge(TypeMissing);   

     }       

 public void InsertTable(SystemDataDataTable dt, string ws, int startX, int startY)//将内存中数据表格插入到MicrosoftOfficeInteropExcel指定工作表的指定位置 为在使用模板时控制格式时使用一       

 {            

for (int i = 0; i  <= dtRowsCount - 1; i++)       

    {             

   for (int j = 0; j  <= dtColumnsCount - 1; j++)        

        {                    

GetSheet(ws)Cells[startX+i, j + startY] = dtRows[i][j]ToString();      

          }        

    }      

  }       

 public void InsertTable(SystemDataDataTable dt, MicrosoftOfficeInteropExcelWorksheet ws, int startX, int startY)//将内存中数据表格插入到MicrosoftOfficeInteropExcel指定工作表的指定位置二       

 {           

 for (int i = 0; i  <= dtRowsCount - 1; i++)      

      {                

for (int j = 0; j  <= dtColumnsCount - 1; j++)          

      {                   

 wsCells[startX+i, j + startY] = dtRows[i][j];             

   }           

 }      

  }        

public void AddTable(SystemDataDataTable dt, string ws, int startX, int startY)//将内存中数据表格添加到MicrosoftOfficeInteropExcel指定工作表的指定位置一       

 {           

 for (int i = 0; i  <= dtRowsCount - 1; i++)      

      {               

for (int j = 0; j  <= dtColumnsCount - 1; j++)         

       {                   

 GetSheet(ws)Cells[i + startX, j + startY] = dtRows[i][j];           

     }         

   }       

 }        

public void AddTable(SystemDataDataTable dt, MicrosoftOfficeInteropExcelWorksheet ws, int startX, int startY)//将内存中数据表格添加到MicrosoftOfficeInteropExcel指定工作表的指定位置二      

  {          

  for (int i = 0; i  <= dtRowsCount - 1; i++)         

   {              

  for (int j = 0; j  <= dtColumnsCount - 1; j++)             

   {                    

wsCells[i + startX, j + startY] = dtRows[i][j];            

    }          

  }       

 }      

  public void InsertPictures(string Filename, string ws)        //插入 *** 作一      

  {           

 GetSheet(ws)ShapesAddPicture(Filename, MsoTriStatemsoFalse, MsoTriStatemsoTrue, 10, 10, 150, 150);            //后面的数字表示位置      

  }      

  //public void InsertPictures(string Filename, string ws, int Height, int Width)        //插入 *** 作二        

//{      

  //    GetSheet(ws)ShapesAddPicture(Filename, MsoTriStatemsoFalse, MsoTriStatemsoTrue, 10, 10, 150, 150);      

  //    GetSheet(ws)Shapesget_Range(TypeMissing)Height = Height;      

  //    GetSheet(ws)Shapesget_Range(TypeMissing)Width = Width;        

//}       

 //public void InsertPictures(string Filename, string ws, int left, int top, int Height, int Width)        //插入 *** 作三        

//{       

 //    GetSheet(ws)ShapesAddPicture(Filename, MsoTriStatemsoFalse, MsoTriStatemsoTrue, 10, 10, 150, 150);       

 //    GetSheet(ws)Shapesget_Range(TypeMissing)IncrementLeft(left);       

 //    GetSheet(ws)Shapesget_Range(TypeMissing)IncrementTop(top);     

   //    GetSheet(ws)Shapesget_Range(TypeMissing)Height = Height;        

//    GetSheet(ws)Shapesget_Range(TypeMissing)Width = Width;        

//}        

public void InsertActiveChart(MicrosoftOfficeInteropExcelXlChartType ChartType, string ws, int DataSourcesX1, int DataSourcesY1, int DataSourcesX2, int DataSourcesY2, MicrosoftOfficeInteropExcelXlRowCol ChartDataType)       

 //插入图表 *** 作       

 {            

ChartDataType = MicrosoftOfficeInteropExcelXlRowColxlColumns;            wbChartsAdd(TypeMissing, TypeMissing, TypeMissing, TypeMissing);        

    {                

wbActiveChartChartType = ChartType;   

             wbActiveChartSetSourceData(GetSheet(ws)get_Range(GetSheet(ws)Cells[DataSourcesX1, DataSourcesY1], GetSheet(ws)Cells[DataSourcesX2, DataSourcesY2]), ChartDataType);     

           wbActiveChartLocation(MicrosoftOfficeInteropExcelXlChartLocationxlLocationAsObject, ws);          

  }      

  }     

   public bool Save()        //保存文档   

     {           

 if (mFilename == "")          

  {               

 return false;           

 }           

 else         

   {             

   try            

    {                    

wbSave();                 

   return true;             

   }               

 catch (Exception ex)           

     {                    

return false;             

   }           

 }        

}       

 public bool SaveAs(object FileName)        //文档另存为       

 {            

try         

   {              

  wbSaveAs(FileName, TypeMissing, TypeMissing, TypeMissing, TypeMissing, TypeMissing, MicrosoftOfficeInteropExcelXlSaveAsAccessModexlExclusive, TypeMissing, TypeMissing, TypeMissing, TypeMissing, TypeMissing);     

           return true;          

  }            

catch (Exception ex)          

 {                

return false;      

      }     

   }      

  public void Close()        //关闭一个MicrosoftOfficeInteropExcel对象,销毁对象      

  {          

  //wbSave();          

  wbClose(TypeMissing, TypeMissing, TypeMissing);           

 wbsClose();           

 appQuit();          

  wb = null;            

wbs = null;            

app = null;            

GCCollect();       

 }    

}

}

package edusjtuerplabpoi;

import javaioInputStream&ch=wwxqychain" target="_blank" class="link-baike">FileInputStream;

import javaioFileNotFoundException;

import javaioIOException;

import javaioInputStream;

import javatextSimpleDateFormat;

import javautilDate;

import javautilHashMap;

import javautilMap;

import orgapachepoihssfusermodelHSSFCell;

import orgapachepoihssfusermodelHSSFDateUtil;

import orgapachepoihssfusermodelHSSFRow;

import orgapachepoihssfusermodelHSSFSheet;

import orgapachepoihssfusermodelHSSFWorkbook;

import orgapachepoipoifsfilesystemPOIFSFileSystem;

/

   *** 作Excel表格的功能类

 /

public class ExcelReader {

    private POIFSFileSystem fs;

    private HSSFWorkbook wb;

    private HSSFSheet sheet;

    private HSSFRow row;

    /

      读取Excel表格表头的内容

      @param InputStream

      @return String 表头内容的数组

     /

    public String[] readExcelTitle(InputStream is) {

        try {

            fs = new POIFSFileSystem(is);

            wb = new HSSFWorkbook(fs);

        } catch (IOException e) {

            eprintStackTrace();

        }

        sheet = wbgetSheetAt(0);

        row = sheetgetRow(0);

        // 标题总列数

        int colNum = rowgetPhysicalNumberOfCells();

        Systemoutprintln("colNum:" + colNum);

        String[] title = new String[colNum];

        for (int i = 0; i < colNum; i++) {

            //title[i] = getStringCellValue(rowgetCell((short) i));

            title[i] = getCellFormatValue(rowgetCell((short) i));

        }

        return title;

    }

    /

      读取Excel数据内容

      @param InputStream

      @return Map 包含单元格数据内容的Map对象

     /

    public Map<Integer, String> readExcelContent(InputStream is) {

        Map<Integer, String> content = new HashMap<Integer, String>();

        String str = "";

        try {

            fs = new POIFSFileSystem(is);

            wb = new HSSFWorkbook(fs);

        } catch (IOException e) {

            eprintStackTrace();

        }

        sheet = wbgetSheetAt(0);

        // 得到总行数

        int rowNum = sheetgetLastRowNum();

        row = sheetgetRow(0);

        int colNum = rowgetPhysicalNumberOfCells();

        // 正文内容应该从第二行开始,第一行为表头的标题

        for (int i = 1; i <= rowNum; i++) {

            row = sheetgetRow(i);

            int j = 0;

            while (j < colNum) {

                // 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据

                // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean

                // str += getStringCellValue(rowgetCell((short) j))trim() +

                // "-";

                str += getCellFormatValue(rowgetCell((short) j))trim() + "    ";

                j++;

            }

            contentput(i, str);

            str = "";

        }

        return content;

    }

    /

      获取单元格数据内容为字符串类型的数据

      

      @param cell Excel单元格

      @return String 单元格数据内容

     /

    private String getStringCellValue(HSSFCell cell) {

        String strCell = "";

        switch (cellgetCellType()) {

        case HSSFCellCELL_TYPE_STRING:

            strCell = cellgetStringCellValue();

            break;

        case HSSFCellCELL_TYPE_NUMERIC:

            strCell = StringvalueOf(cellgetNumericCellValue());

            break;

        case HSSFCellCELL_TYPE_BOOLEAN:

            strCell = StringvalueOf(cellgetBooleanCellValue());

            break;

        case HSSFCellCELL_TYPE_BLANK:

            strCell = "";

            break;

        default:

            strCell = "";

            break;

        }

        if (strCellequals("") || strCell == null) {

            return "";

        }

        if (cell == null) {

            return "";

        }

        return strCell;

    }

    /

      获取单元格数据内容为日期类型的数据

      

      @param cell

                 Excel单元格

      @return String 单元格数据内容

     /

    private String getDateCellValue(HSSFCell cell) {

        String result = "";

        try {

            int cellType = cellgetCellType();

            if (cellType == HSSFCellCELL_TYPE_NUMERIC) {

                Date date = cellgetDateCellValue();

                result = (dategetYear() + 1900) + "-" + (dategetMonth() + 1)

                        + "-" + dategetDate();

            } else if (cellType == HSSFCellCELL_TYPE_STRING) {

                String date = getStringCellValue(cell);

                result = datereplaceAll("[年月]", "-")replace("日", "")trim();

            } else if (cellType == HSSFCellCELL_TYPE_BLANK) {

                result = "";

            }

        } catch (Exception e) {

            Systemoutprintln("日期格式不正确!");

            eprintStackTrace();

        }

        return result;

    }

    /

      根据HSSFCell类型设置数据

      @param cell

      @return

     /

    private String getCellFormatValue(HSSFCell cell) {

        String cellvalue = "";

        if (cell != null) {

            // 判断当前Cell的Type

            switch (cellgetCellType()) {

            // 如果当前Cell的Type为NUMERIC

            case HSSFCellCELL_TYPE_NUMERIC:

            case HSSFCellCELL_TYPE_FORMULA: {

                // 判断当前的cell是否为Date

                if (HSSFDateUtilisCellDateFormatted(cell)) {

                    // 如果是Date类型则,转化为Data格式

                    //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00

                    //cellvalue = cellgetDateCellValue()toLocaleString();

                    //方法2:这样子的data格式是不带带时分秒的:2011-10-12

                    Date date = cellgetDateCellValue();

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    cellvalue = sdfformat(date);

                }

                // 如果是纯数字

                else {

                    // 取得当前Cell的数值

                    cellvalue = StringvalueOf(cellgetNumericCellValue());

                }

                break;

            }

            // 如果当前Cell的Type为STRIN

            case HSSFCellCELL_TYPE_STRING:

                // 取得当前的Cell字符串

                cellvalue = cellgetRichStringCellValue()getString();

                break;

            // 默认的Cell值

            default:

                cellvalue = " ";

            }

        } else {

            cellvalue = "";

        }

        return cellvalue;

    }

    public static void main(String[] args) {

        try {

            // 对读取Excel表格标题测试

            InputStream is = new FileInputStream("d:\\test2xls");

            ExcelReader excelReader = new ExcelReader();

            String[] title = excelReaderreadExcelTitle(is);

            Systemoutprintln("获得Excel表格的标题:");

            for (String s : title) {

                Systemoutprint(s + " ");

            }

            // 对读取Excel表格内容测试

            InputStream is2 = new FileInputStream("d:\\test2xls");

            Map<Integer, String> map = excelReaderreadExcelContent(is2);

            Systemoutprintln("获得Excel表格的内容:");

            for (int i = 1; i <= mapsize(); i++) {

                Systemoutprintln(mapget(i));

            }

        } catch (FileNotFoundException e) {

            Systemoutprintln("未找到指定路径的文件!");

            eprintStackTrace();

        }

    }

}

以上就是关于C# 读取EXCEL文件的三种经典方法全部的内容,包括:C# 读取EXCEL文件的三种经典方法、java poi怎么获取excel单元格的内容、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9553906.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-29
下一篇2023-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存