• C#处理Excel


    C#处理Excel

    Excel C# NPOI OleDb


    前言

    最近需要对Excel进行加密解密操作,本身是一个简单的事情,通过 OleDbConnection可以很容易进行操作Excel,或者也可以用第三方dll如NPOI进行操作。

    OleDb

    用OleDb方法几乎和SqlConnection一模一样,基本上把前缀Sql改成OleDb即可,不过有几个小细节需要注意。
    1. 我们可以把一个Excel当成一个数据源
    2. 每个sheet可以看成一张表
    3. 需要注意的是你在Excel看到的sheet名称后面需要加上$才是真正的sheet名字。

    具体操作

    我在此简单封装了下,取名为OleDbHelper,代码如下:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Data;
    4. using System.Data.OleDb;
    5. namespace ExcelDataEncipher
    6. {
    7. class OleDbHelper
    8. {
    9. private readonly string _connstr;
    10. //当前Sheet集合
    11. public IEnumerable<string> SheetNames { get; set; }
    12. //通过在外部传入数据源的名称来连接
    13. public OleDbHelper(string name)
    14. {
    15. _connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;ReadOnly=False;HDR=Yes;'", name);
    16. //这个连接串可以连接2003的,高版本Excel的连接串可能有所变化,由于我需要进行加密解密操作需要修改excel,所以ReadOnly设置为false
    17. //同时HDR设置为Yes代表第一行是标题,不做为数据使用
    18. this.GetSheetName();//获取所有Sheet名称
    19. }
    20. private void GetSheetName()
    21. {
    22. using (OleDbConnection conn = new OleDbConnection(_connstr))
    23. {
    24. conn.Open();
    25. using (DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "Table"}))
    26. {
    27. //包含excel中表名的字符串数组
    28. if (dtSheetName != null)
    29. {
    30. List<string> strTableNames = new List<string>();
    31. for (int k = 0; k < dtSheetName.Rows.Count; k++)
    32. {
    33. strTableNames.Add(dtSheetName.Rows[k]["TABLE_NAME"].ToString());
    34. }//获取Sheet名称
    35. SheetNames = strTableNames;
    36. }
    37. }
    38. }
    39. }
    40. public int ExecuteNonQuery(string oleDb,
    41. params OleDbParameter[] parameters)
    42. {
    43. using (OleDbConnection conn = new OleDbConnection(_connstr))
    44. {
    45. conn.Open();
    46. using (OleDbCommand cmd = conn.CreateCommand())
    47. {
    48. cmd.CommandText = oleDb;
    49. cmd.Parameters.AddRange(parameters);
    50. return cmd.ExecuteNonQuery();
    51. }
    52. }
    53. }
    54. public object ExecuteScalar(string oleDb,
    55. params OleDbParameter[] parameters)
    56. {
    57. using (OleDbConnection conn = new OleDbConnection(_connstr))
    58. {
    59. conn.Open();
    60. using (OleDbCommand cmd = conn.CreateCommand())
    61. {
    62. cmd.CommandText = oleDb;
    63. cmd.Parameters.AddRange(parameters);
    64. return cmd.ExecuteScalar();
    65. }
    66. }
    67. }
    68. public DataTable ExecuteDataTable(string oleDb,
    69. params OleDbParameter[] parameters)
    70. {
    71. using (OleDbConnection conn = new OleDbConnection(_connstr))
    72. {
    73. conn.Open();
    74. using (OleDbCommand cmd = conn.CreateCommand())
    75. {
    76. cmd.CommandText = oleDb;
    77. cmd.Parameters.AddRange(parameters);
    78. DataSet dataset = new DataSet();
    79. OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
    80. adapter.Fill(dataset);
    81. return dataset.Tables[0];
    82. }
    83. }
    84. }
    85. public static object FromDbValue(object value)
    86. {
    87. if (value == DBNull.Value)
    88. {
    89. return null;
    90. }
    91. else
    92. {
    93. return value;
    94. }
    95. }
    96. public static object ToDbValue(object value)
    97. {
    98. if (value == null)
    99. {
    100. return DBNull.Value;
    101. }
    102. else
    103. {
    104. return value;
    105. }
    106. }
    107. }
    108. }

    可以发现操作和对数据库操作一模一样

    我通过OpenFileDialog选择需要操作的文件

    1. foreach (var filename in openFile.FileNames)
    2. {
    3. string name = filename;
    4. _oleDbHelper = new OleDbHelper(name); //获取表
    5. string sheetName = _oleDbHelper.SheetNames.SingleOrDefault(s => s.Contains("Detail"));//查看名称是否包含Detail的sheet
    6. DataTable table = null;
    7. try
    8. {
    9. table = _oleDbHelper.ExecuteDataTable(string.Format("select * from [{0}]", sheetName));//将其转换为datatable
    10. }
    11. catch (Exception msg)
    12. {
    13. throw new Exception(msg.Message);
    14. }
    15. if (table.Rows.Count < 0)
    16. {
    17. MessageBox.Show("未找到任何记录");
    18. return;
    19. }
    20. for (int i = 0; i < table.Rows.Count; i++)
    21. {
    22. ...//处理数据
    23. try
    24. {
    25. ...//处理数据
    26. _oleDbHelper.ExecuteNonQuery(
    27. string.Format(
    28. "update [{0}] set [AccountNumber] = '{1}',[AccountName] = '{2}',[Price] = '{3}' where [Id] = '{4}'",
    29. sheetName, table.Rows[i]["AccountNumber"], table.Rows[i]["AccountName"], table.Rows[i]["Price"],
    30. table.Rows[i]["Id"]));
    31. //更新excel
    32. }
    33. catch (Exception msg)
    34. {
    35. throw new Exception(msg.Message);
    36. }
    37. }
    38. }

    本来通过参数化的形式进行更新,但是一直报错,不知道什么情况
    通过OleDb修改excel速度非常的慢,我的excel表 5行28列需要修改其中3列的数据需要1秒多,不知道是不是因为更新一个表格他会刷新整张excel还是为什么

    OleDb

    NPOI

    因为速度实在太慢,我不得不寻找其他的解决方法
    NPOI是一个开源的读写Excel、Word等项目,他的优点是不需要在机子上安装office也可以进行操作,而且读写速度还是非常快的。

    具体操作

    这里我在网上下载了别人的封装好的一个帮助类,略做了修改来适配我的项目

    1. /*******************************************************************
    2. * 版权所有:
    3. * 类 名 称:ExcelHelper
    4. * 作 者:zk
    5. * 电子邮箱:
    6. * 创建日期:2012/2/25 10:17:21
    7. * 修改描述:从excel导入datatable时,可以导入日期类型。
    8. * 但对excel中的日期类型有一定要求,要求至少是yyyy/mm/dd类型日期; *
    9. * 修改描述:将datatable导入excel中,对类型为字符串的数字进行处理,
    10. * 导出数字为double类型;
    11. *
    12. *
    13. * *******************************************************************/
    14. using System;
    15. using System.Collections;
    16. using System.Collections.Generic;
    17. using System.Data;
    18. using System.IO;
    19. using System.Text;
    20. using System.Text.RegularExpressions;
    21. using NPOI.HSSF.UserModel;
    22. using NPOI.SS.Formula.Eval;
    23. using NPOI.SS.UserModel;
    24. using NPOI.SS.Util;
    25. namespace ExcelDataEncipher
    26. {
    27. public static class ExcelHelper
    28. {
    29. //private static WriteLog wl = new WriteLog();a
    30. #region 从datatable中将数据导出到excel
    31. /// <summary>
    32. /// DataTable导出到Excel的MemoryStream
    33. /// </summary>
    34. /// <param name="dtSource">源DataTable</param>
    35. /// <param name="strHeaderText">表头文本</param>
    36. public static MemoryStream ExportDT(DataTable dtSource, string strHeaderText)
    37. {
    38. HSSFWorkbook workbook = new HSSFWorkbook();
    39. HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
    40. #region 右击文件 属性信息
    41. //{
    42. // DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
    43. // dsi.Company = "http://www.yongfa365.com/";
    44. // workbook.DocumentSummaryInformation = dsi;
    45. // SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
    46. // si.Author = "柳永法"; //填加xls文件作者信息
    47. // si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
    48. // si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
    49. // si.Comments = "说明信息"; //填加xls文件作者信息
    50. // si.Title = "NPOI测试"; //填加xls文件标题信息
    51. // si.Subject = "NPOI测试Demo"; //填加文件主题信息
    52. // si.CreateDateTime = DateTime.Now;
    53. // workbook.SummaryInformation = si;
    54. //}
    55. #endregion
    56. HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
    57. HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
    58. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
    59. //取得列宽
    60. int[] arrColWidth = new int[dtSource.Columns.Count];
    61. foreach (DataColumn item in dtSource.Columns)
    62. {
    63. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
    64. }
    65. for (int i = 0; i < dtSource.Rows.Count; i++)
    66. {
    67. for (int j = 0; j < dtSource.Columns.Count; j++)
    68. {
    69. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
    70. if (intTemp > arrColWidth[j])
    71. {
    72. arrColWidth[j] = intTemp;
    73. }
    74. }
    75. }
    76. int rowIndex = 0;
    77. foreach (DataRow row in dtSource.Rows)
    78. {
    79. #region 新建表,填充表头,填充列头,样式
    80. if (rowIndex == 65535 || rowIndex == 0)
    81. {
    82. if (rowIndex != 0)
    83. {
    84. sheet = workbook.CreateSheet() as HSSFSheet;
    85. }
    86. #region 表头及样式
    87. {
    88. HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
    89. headerRow.HeightInPoints = 25;
    90. headerRow.CreateCell(0).SetCellValue(strHeaderText);
    91. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
    92. headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
    93. HSSFFont font = workbook.CreateFont() as HSSFFont;
    94. font.FontHeightInPoints = 20;
    95. font.Boldweight = 700;
    96. headStyle.SetFont(font);
    97. headerRow.GetCell(0).CellStyle = headStyle;
    98. sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
    99. //headerRow.Dispose();
    100. }
    101. #endregion
    102. #region 列头及样式
    103. {
    104. HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow;
    105. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
    106. headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
    107. HSSFFont font = workbook.CreateFont() as HSSFFont;
    108. font.FontHeightInPoints = 10;
    109. font.Boldweight = 700;
    110. headStyle.SetFont(font);
    111. foreach (DataColumn column in dtSource.Columns)
    112. {
    113. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
    114. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
    115. //设置列宽
    116. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
    117. }
    118. //headerRow.Dispose();
    119. }
    120. #endregion
    121. rowIndex = 2;
    122. }
    123. #endregion
    124. #region 填充内容
    125. HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
    126. foreach (DataColumn column in dtSource.Columns)
    127. {
    128. HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
    129. string drValue = row[column].ToString();
    130. switch (column.DataType.ToString())
    131. {
    132. case "System.String": //字符串类型
    133. double result;
    134. if (isNumeric(drValue, out result))
    135. {
    136. double.TryParse(drValue, out result);
    137. newCell.SetCellValue(result);
    138. break;
    139. }
    140. else
    141. {
    142. newCell.SetCellValue(drValue);
    143. break;
    144. }
    145. case "System.DateTime": //日期类型
    146. DateTime dateV;
    147. DateTime.TryParse(drValue, out dateV);
    148. newCell.SetCellValue(dateV);
    149. newCell.CellStyle = dateStyle; //格式化显示
    150. break;
    151. case "System.Boolean": //布尔型
    152. bool boolV = false;
    153. bool.TryParse(drValue, out boolV);
    154. newCell.SetCellValue(boolV);
    155. break;
    156. case "System.Int16": //整型
    157. case "System.Int32":
    158. case "System.Int64":
    159. case "System.Byte":
    160. int intV = 0;
    161. int.TryParse(drValue, out intV);
    162. newCell.SetCellValue(intV);
    163. break;
    164. case "System.Decimal": //浮点型
    165. case "System.Double":
    166. double doubV = 0;
    167. double.TryParse(drValue, out doubV);
    168. newCell.SetCellValue(doubV);
    169. break;
    170. case "System.DBNull": //空值处理
    171. newCell.SetCellValue("");
    172. break;
    173. default:
    174. newCell.SetCellValue("");
    175. break;
    176. }
    177. }
    178. #endregion
    179. rowIndex++;
    180. }
    181. using (MemoryStream ms = new MemoryStream())
    182. {
    183. workbook.Write(ms);
    184. ms.Flush();
    185. ms.Position = 0;
    186. return ms;
    187. }
    188. }
    189. /// <summary>
    190. /// DataTable导出到Excel文件
    191. /// </summary>
    192. /// <param name="dtSource">源DataTable</param>
    193. /// <param name="strHeaderText">表头文本</param>
    194. /// <param name="strFileName">保存位置</param>
    195. public static void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName)
    196. {
    197. using (MemoryStream ms = ExportDT(dtSource, strHeaderText))
    198. {
    199. using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
    200. {
    201. byte[] data = ms.ToArray();
    202. fs.Write(data, 0, data.Length);
    203. fs.Flush();
    204. }
    205. }
    206. }
    207. #endregion
    208. #region 从excel中将数据导出到datatable
    209. /// <summary>读取excel
    210. /// 默认第一行为标头
    211. /// </summary>
    212. /// <param name="strFileName">excel文档路径</param>
    213. /// <returns></returns>
    214. public static DataTable ImportExceltoDt(string strFileName,string sheetName,bool includeTitle = true)
    215. {
    216. DataTable dt = new DataTable();
    217. HSSFWorkbook hssfworkbook;
    218. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
    219. {
    220. hssfworkbook = new HSSFWorkbook(file);
    221. }
    222. HSSFSheet sheet = hssfworkbook.GetSheet(sheetName) as HSSFSheet;
    223. if (sheet == null) return null;
    224. dt = ImportDt(sheet, 0, includeTitle);
    225. return dt;
    226. }
    227. /// <summary>
    228. /// 读取excel
    229. /// </summary>
    230. /// <param name="strFileName">excel文件路径</param>
    231. /// <param name="sheet">需要导出的sheet</param>
    232. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
    233. /// <returns></returns>
    234. public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex)
    235. {
    236. HSSFWorkbook workbook;
    237. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
    238. {
    239. workbook = new HSSFWorkbook(file);
    240. }
    241. HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
    242. DataTable table = new DataTable();
    243. table = ImportDt(sheet, HeaderRowIndex, true);
    244. //ExcelFileStream.Close();
    245. workbook = null;
    246. sheet = null;
    247. return table;
    248. }
    249. /// <summary>
    250. /// 读取excel
    251. /// </summary>
    252. /// <param name="strFileName">excel文件路径</param>
    253. /// <param name="sheet">需要导出的sheet序号</param>
    254. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
    255. /// <returns></returns>
    256. public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex)
    257. {
    258. HSSFWorkbook workbook;
    259. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
    260. {
    261. workbook = new HSSFWorkbook(file);
    262. }
    263. HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
    264. DataTable table = new DataTable();
    265. table = ImportDt(sheet, HeaderRowIndex, true);
    266. //ExcelFileStream.Close();
    267. workbook = null;
    268. sheet = null;
    269. return table;
    270. }
    271. /// <summary>
    272. /// 读取excel
    273. /// </summary>
    274. /// <param name="strFileName">excel文件路径</param>
    275. /// <param name="sheet">需要导出的sheet</param>
    276. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
    277. /// <returns></returns>
    278. public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex, bool needHeader)
    279. {
    280. HSSFWorkbook workbook;
    281. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
    282. {
    283. workbook = new HSSFWorkbook(file);
    284. }
    285. HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
    286. DataTable table = new DataTable();
    287. table = ImportDt(sheet, HeaderRowIndex, needHeader);
    288. //ExcelFileStream.Close();
    289. workbook = null;
    290. sheet = null;
    291. return table;
    292. }
    293. /// <summary>
    294. /// 读取excel
    295. /// </summary>
    296. /// <param name="strFileName">excel文件路径</param>
    297. /// <param name="sheet">需要导出的sheet序号</param>
    298. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
    299. /// <returns></returns>
    300. public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader)
    301. {
    302. HSSFWorkbook workbook;
    303. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
    304. {
    305. workbook = new HSSFWorkbook(file);
    306. }
    307. HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
    308. DataTable table = new DataTable();
    309. table = ImportDt(sheet, HeaderRowIndex, needHeader);
    310. //ExcelFileStream.Close();
    311. workbook = null;
    312. sheet = null;
    313. return table;
    314. }
    315. /// <summary>
    316. /// 将制定sheet中的数据导出到datatable中
    317. /// </summary>
    318. /// <param name="sheet">需要导出的sheet</param>
    319. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
    320. /// <returns></returns>
    321. static DataTable ImportDt(HSSFSheet sheet, int HeaderRowIndex, bool needHeader)
    322. {
    323. DataTable table = new DataTable();
    324. HSSFRow headerRow;
    325. int cellCount;
    326. try
    327. {
    328. if (HeaderRowIndex < 0 || !needHeader)
    329. {
    330. headerRow = sheet.GetRow(0) as HSSFRow;
    331. cellCount = headerRow.LastCellNum;
    332. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
    333. {
    334. DataColumn column = new DataColumn(Convert.ToString(i));
    335. table.Columns.Add(column);
    336. }
    337. }
    338. else
    339. {
    340. headerRow = sheet.GetRow(HeaderRowIndex) as HSSFRow;
    341. cellCount = headerRow.LastCellNum;
    342. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
    343. {
    344. if (headerRow.GetCell(i) == null)
    345. {
    346. if (table.Columns.IndexOf(Convert.ToString(i)) > 0)
    347. {
    348. DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
    349. table.Columns.Add(column);
    350. }
    351. else
    352. {
    353. DataColumn column = new DataColumn(Convert.ToString(i));
    354. table.Columns.Add(column);
    355. }
    356. }
    357. else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
    358. {
    359. DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
    360. table.Columns.Add(column);
    361. }
    362. else
    363. {
    364. DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
    365. table.Columns.Add(column);
    366. }
    367. }
    368. }
    369. int rowCount = sheet.LastRowNum;
    370. for (int i = (HeaderRowIndex + 1); i <= rowCount; i++)
    371. {
    372. try
    373. {
    374. HSSFRow row;
    375. if (sheet.GetRow(i) == null)
    376. {
    377. row = sheet.CreateRow(i) as HSSFRow;
    378. }
    379. else
    380. {
    381. row = sheet.GetRow(i) as HSSFRow;
    382. }
    383. DataRow dataRow = table.NewRow();
    384. for (int j = row.FirstCellNum; j < cellCount; j++)
    385. {
    386. try
    387. {
    388. if (row.GetCell(j) != null)
    389. {
    390. switch (row.GetCell(j).CellType)
    391. {
    392. case CellType.String:
    393. string str = row.GetCell(j).StringCellValue;
    394. if (!string.IsNullOrEmpty(str))
    395. {
    396. dataRow[j] = str.ToString();
    397. }
    398. else
    399. {
    400. dataRow[j] = null;
    401. }
    402. break;
    403. case CellType.Numeric:
    404. if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
    405. {
    406. dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
    407. }
    408. else
    409. {
    410. dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
    411. }
    412. break;
    413. case CellType.Boolean:
    414. dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
    415. break;
    416. case CellType.Error:
    417. dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
    418. break;
    419. case CellType.Formula:
    420. switch (row.GetCell(j).CachedFormulaResultType)
    421. {
    422. case CellType.String:
    423. string strFORMULA = row.GetCell(j).StringCellValue;
    424. if (!string.IsNullOrEmpty(strFORMULA))
    425. {
    426. dataRow[j] = strFORMULA.ToString();
    427. }
    428. else
    429. {
    430. dataRow[j] = null;
    431. }
    432. break;
    433. case CellType.Numeric:
    434. dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
    435. break;
    436. case CellType.Boolean:
    437. dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
    438. break;
    439. case CellType.Error:
    440. dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
    441. break;
    442. default:
    443. dataRow[j] = "";
    444. break;
    445. }
    446. break;
    447. default:
    448. dataRow[j] = "";
    449. break;
    450. }
    451. }
    452. }
    453. catch (Exception exception)
    454. {
    455. throw new Exception(exception.Message);
    456. //wl.WriteLogs(exception.ToString());
    457. }
    458. }
    459. table.Rows.Add(dataRow);
    460. }
    461. catch (Exception exception)
    462. {
    463. throw new Exception(exception.Message);
    464. //wl.WriteLogs(exception.ToString());
    465. }
    466. }
    467. }
    468. catch (Exception exception)
    469. {
    470. throw new Exception(exception.Message);
    471. //wl.WriteLogs(exception.ToString());
    472. }
    473. return table;
    474. }
    475. #endregion
    476. #region 更新excel中的数据
    477. /// <summary>
    478. /// 更新Excel表格
    479. /// </summary>
    480. /// <param name="outputFile">需更新的excel表格路径</param>
    481. /// <param name="sheetname">sheet名</param>
    482. /// <param name="data"></param>
    483. /// <param name="saveTitle"></param>
    484. public static bool UpdateExcel(string oldFile,string newFile, string sheetname,DataTable data,bool saveTitle = true)
    485. {
    486. try
    487. {
    488. HSSFWorkbook hssfworkbook;
    489. using (FileStream readfile = new FileStream(oldFile, FileMode.Open, FileAccess.Read))
    490. {
    491. hssfworkbook = new HSSFWorkbook(readfile);
    492. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
    493. int currentSheetRowIndex = 0;
    494. if (saveTitle) currentSheetRowIndex = 1;
    495. for (int i = 0; i < data.Rows.Count; i++, currentSheetRowIndex++)
    496. {
    497. for (int j = 0; j < data.Columns.Count; j++)
    498. {
    499. if (sheet1.GetRow(currentSheetRowIndex) == null)
    500. sheet1.CreateRow(currentSheetRowIndex);
    501. if (sheet1.GetRow(currentSheetRowIndex).GetCell(j) == null)
    502. sheet1.GetRow(currentSheetRowIndex).CreateCell(j);
    503. sheet1.GetRow(currentSheetRowIndex).GetCell(j).SetCellValue(data.Rows[i][j].ToString());
    504. }
    505. }
    506. }
    507. using (FileStream writefile = new FileStream(newFile, FileMode.Create, FileAccess.Write))
    508. {
    509. hssfworkbook.Write(writefile);
    510. }
    511. }
    512. catch (IOException ioException)
    513. {
    514. throw new IOException(ioException.Message);
    515. }
    516. catch (UnauthorizedAccessException unauthorizedAccessException)
    517. {
    518. throw new UnauthorizedAccessException(unauthorizedAccessException.Message);
    519. }
    520. catch (Exception ex)
    521. {
    522. throw new Exception(ex.Message);
    523. // wl.WriteLogs(ex.ToString());
    524. }
    525. return true;
    526. }
    527. /// <summary>
    528. /// 更新Excel表格
    529. /// </summary>
    530. /// <param name="outputFile">需更新的excel表格路径</param>
    531. /// <param name="sheetname">sheet名</param>
    532. /// <param name="updateData">需更新的数据</param>
    533. /// <param name="coluids">需更新的列号</param>
    534. /// <param name="rowid">需更新的开始行号</param>
    535. public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid)
    536. {
    537. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    538. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    539. readfile.Close();
    540. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
    541. for (int j = 0; j < coluids.Length; j++)
    542. {
    543. for (int i = 0; i < updateData[j].Length; i++)
    544. {
    545. try
    546. {
    547. if (sheet1.GetRow(i + rowid) == null)
    548. {
    549. sheet1.CreateRow(i + rowid);
    550. }
    551. if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
    552. {
    553. sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
    554. }
    555. sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
    556. }
    557. catch (Exception ex)
    558. {
    559. // wl.WriteLogs(ex.ToString());
    560. }
    561. }
    562. }
    563. try
    564. {
    565. FileStream writefile = new FileStream(outputFile, FileMode.Create);
    566. hssfworkbook.Write(writefile);
    567. writefile.Close();
    568. }
    569. catch (Exception ex)
    570. {
    571. //wl.WriteLogs(ex.ToString());
    572. }
    573. }
    574. /// <summary>
    575. /// 更新Excel表格
    576. /// </summary>
    577. /// <param name="outputFile">需更新的excel表格路径</param>
    578. /// <param name="sheetname">sheet名</param>
    579. /// <param name="updateData">需更新的数据</param>
    580. /// <param name="coluid">需更新的列号</param>
    581. /// <param name="rowid">需更新的开始行号</param>
    582. public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid)
    583. {
    584. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    585. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    586. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
    587. for (int i = 0; i < updateData.Length; i++)
    588. {
    589. try
    590. {
    591. if (sheet1.GetRow(i + rowid) == null)
    592. {
    593. sheet1.CreateRow(i + rowid);
    594. }
    595. if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
    596. {
    597. sheet1.GetRow(i + rowid).CreateCell(coluid);
    598. }
    599. sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
    600. }
    601. catch (Exception ex)
    602. {
    603. throw new Exception(ex.Message);
    604. //wl.WriteLogs(ex.ToString());
    605. throw;
    606. }
    607. }
    608. try
    609. {
    610. readfile.Close();
    611. FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
    612. hssfworkbook.Write(writefile);
    613. writefile.Close();
    614. }
    615. catch (Exception ex)
    616. {
    617. //wl.WriteLogs(ex.ToString());
    618. }
    619. }
    620. /// <summary>
    621. /// 更新Excel表格
    622. /// </summary>
    623. /// <param name="outputFile">需更新的excel表格路径</param>
    624. /// <param name="sheetname">sheet名</param>
    625. /// <param name="updateData">需更新的数据</param>
    626. /// <param name="coluids">需更新的列号</param>
    627. /// <param name="rowid">需更新的开始行号</param>
    628. public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid)
    629. {
    630. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    631. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    632. readfile.Close();
    633. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
    634. for (int j = 0; j < coluids.Length; j++)
    635. {
    636. for (int i = 0; i < updateData[j].Length; i++)
    637. {
    638. try
    639. {
    640. if (sheet1.GetRow(i + rowid) == null)
    641. {
    642. sheet1.CreateRow(i + rowid);
    643. }
    644. if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
    645. {
    646. sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
    647. }
    648. sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
    649. }
    650. catch (Exception ex)
    651. {
    652. //wl.WriteLogs(ex.ToString());
    653. }
    654. }
    655. }
    656. try
    657. {
    658. FileStream writefile = new FileStream(outputFile, FileMode.Create);
    659. hssfworkbook.Write(writefile);
    660. writefile.Close();
    661. }
    662. catch (Exception ex)
    663. {
    664. //wl.WriteLogs(ex.ToString());
    665. }
    666. }
    667. #endregion
    668. public static int GetSheetNumber(string outputFile)
    669. {
    670. int number = 0;
    671. try
    672. {
    673. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    674. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    675. number = hssfworkbook.NumberOfSheets;
    676. }
    677. catch (Exception exception)
    678. {
    679. //wl.WriteLogs(exception.ToString());
    680. }
    681. return number;
    682. }
    683. public static ArrayList GetSheetName(string outputFile)
    684. {
    685. ArrayList arrayList = new ArrayList();
    686. try
    687. {
    688. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    689. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    690. for (int i = 0; i < hssfworkbook.NumberOfSheets; i++)
    691. {
    692. arrayList.Add(hssfworkbook.GetSheetName(i));
    693. }
    694. }
    695. catch (Exception exception)
    696. {
    697. //wl.WriteLogs(exception.ToString());
    698. }
    699. return arrayList;
    700. }
    701. public static bool isNumeric(String message, out double result)
    702. {
    703. Regex rex = new Regex(@"^[-]?d+[.]?d*$");
    704. result = -1;
    705. if (rex.IsMatch(message))
    706. {
    707. result = double.Parse(message);
    708. return true;
    709. }
    710. else return false;
    711. }
    712. }
    713. }
    1. DataTable table = ExcelHelper.ImportExceltoDt(name,"Detail");//name是excel的路径txtSheetName是sheet名称
    2. success = ExcelHelper.UpdateExcel(name, newFileName, "Detail", table);//name是原excel名称,这里我需要把处理好的文件另存而不去修改源文件所以我加入了一个新的路径,table是需要保存的数据返回值为bool表示成功或失败

    通过测试NPOI速度为OLEDB的数十倍,

    NPOI

  • 相关阅读:
    第三篇——第二部分——第三文 配置SQL Server镜像——域环境
    DOS命令学习(从入门到精通)
    Cocos2d-x3.0 LoadingBar
    微信对接HIS——微信可查检验结果
    微信iOS SDK文档总结
    Azure编程笔记(4):配置Cloud Service的证书
    android的ViewPager和Animation的一些使用(一)
    小虾米的鳄鱼梦
    Hadoop源码分析21:namenode概要
    Hadoop源码分析20:datanode概要
  • 原文地址:https://www.cnblogs.com/Jack-Blog/p/4692910.html
Copyright © 2020-2023  润新知