C#无需安装Office使用NPOI处理xls到xlsx的转换
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
主代码public static class HSheetExt { /// <summary> /// 将xls中的sheet转为xlsx格式的sheet(保留处理单元格格式以及字体格式) /// </summary> /// <param name="hSSFSheet"></param> /// <param name="dWb"></param> /// <returns></returns> public static XSSFSheet ConvertToXSheet(this HSSFSheet hSSFSheet, XSSFWorkbook dWb) { XSSFSheet xSSFSheet = dWb.CreateSheet() as XSSFSheet; var rowCount = hSSFSheet.LastRowNum;//行数
#region 预定义样式和字体信息 List<XSSFCellStyle> xSSFCellStyles = new List<XSSFCellStyle>(); List<XSSFFont> xSSFFonts = new List<XSSFFont>(); #endregion //列宽度处理 int maxColumnWidth = 256 * 255; var xCommnetsDic = ConvertHCommentToXComment(xSSFSheet, hSSFSheet, xSSFFonts); for (var i = 0; i <= rowCount; i++) { var hRow = hSSFSheet.GetRow(i); if (hRow == null) { continue; } var xRow = xSSFSheet.CreateRow(i); xRow.Height = hRow.Height; var curHRowColumnCount = hRow.LastCellNum;//列数 for(var j = 0;j <= curHRowColumnCount; j++) { var orgWidth = hSSFSheet.GetColumnWidth(i); if (orgWidth > maxColumnWidth) { xSSFSheet.SetColumnWidth(i, maxColumnWidth); } else { xSSFSheet.SetColumnWidth(i, orgWidth); }
XSSFCell xCell = xRow.CreateCell(j) as XSSFCell; HSSFCell hCell = hRow.GetCell(j) as HSSFCell;
ConvertHCellToXCell(hCell, xCell, xSSFCellStyles, xSSFFonts, xCommnetsDic, true); } }
//最后处理合并单元格的相关情况 int sheetMergerCount = hSSFSheet.NumMergedRegions; for (int k = 0; k < sheetMergerCount; k++) xSSFSheet.AddMergedRegion(hSSFSheet.GetMergedRegion(k));
return xSSFSheet; } } 处理批注信息代码 /// <summary>
/// 处理批注信息转换
/// </summary>
/// <param name="xSSFSheet"></param>
/// <param name="hSSFSheet"></param>
/// <param name="xSSFFonts"></param>
/// <returns></returns>
private static Dictionary<CellAddress,XSSFComment> ConvertHCommentToXComment(XSSFSheet xSSFSheet,HSSFSheet hSSFSheet, List<XSSFFont> xSSFFonts)
{
var hCommnetsDic = hSSFSheet.GetCellComments();
var drawing = xSSFSheet.CreateDrawingPatriarch();
Dictionary<CellAddress,XSSFComment> dic = new Dictionary<CellAddress, XSSFComment> ();
foreach (var item in hCommnetsDic)
{
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.AnchorType = item.Value.ClientAnchor.AnchorType;
anchor.Col1 = item.Value.ClientAnchor.Col1;
anchor.Col2 = item.Value.ClientAnchor.Col2;
anchor.Dx1 = item.Value.ClientAnchor.Dx1;
anchor.Dx2 = item.Value.ClientAnchor.Dx2;
anchor.Dy1 = item.Value.ClientAnchor.Dy1;
anchor.Dy2 = item.Value.ClientAnchor.Dy2;
anchor.Row1 = item.Value.ClientAnchor.Row1;
anchor.Row2 = item.Value.ClientAnchor.Row2;
var comment = drawing.CreateCellComment(anchor) as XSSFComment;
comment.Visible = item.Value.Visible;
HSSFRichTextString richText = (HSSFRichTextString)item.Value.String;
int formattingRuns = richText.NumFormattingRuns;
comment.String = new XSSFRichTextString(richText.String);
for (int i = 0; i < formattingRuns; i++)
{
int startIdx = richText.GetIndexOfFormattingRun(i);
short fontIndex = richText.GetFontOfFormattingRun(i);
HSSFFont hSSFFont = hSSFSheet.Workbook.GetFontAt(fontIndex) as HSSFFont;
var xFont = FindXFont(hSSFFont, xSSFFonts, xSSFSheet);
comment.String.ApplyFont(startIdx, richText.Length, xFont);
}
dic.Add(item.Key,comment);
}
return dic;
} 转换单元格信息 /// <summary>
/// 转换单元格信息
/// </summary>
/// <param name="hSSFCell"></param>
/// <param name="xSSFCell"></param>
/// <param name="xSSFCellStyles"></param>
/// <param name="xSSFFonts"></param>
/// <param name="isConvertStyle"></param>
private static void ConvertHCellToXCell(HSSFCell hSSFCell,XSSFCell xSSFCell,List<XSSFCellStyle> xSSFCellStyles, List<XSSFFont> xSSFFonts, Dictionary<CellAddress,XSSFComment> xCommnetsDic, bool isConvertStyle = true)
{
if (hSSFCell != null)
{
var hCellType = hSSFCell.CellType;
if (hSSFCell.CellComment != null)
{
var xCellComment = xCommnetsDic.Where(w => w.Key.Column == hSSFCell.CellComment.Address.Column && w.Key.Row == hSSFCell.CellComment.Address.Row).FirstOrDefault().Value;
xSSFCell.CellComment = xCellComment;
}
switch (hCellType)
{
case NPOI.SS.UserModel.CellType.Numeric:
xSSFCell.SetCellValue(hSSFCell.NumericCellValue);
break;
case NPOI.SS.UserModel.CellType.Unknown:
return;
case NPOI.SS.UserModel.CellType.Boolean:
xSSFCell.SetCellValue(hSSFCell.BooleanCellValue);
break;
case NPOI.SS.UserModel.CellType.Blank:
return;
case NPOI.SS.UserModel.CellType.Formula:
xSSFCell.SetCellValue(hSSFCell.CellFormula);
break;
case NPOI.SS.UserModel.CellType.Error:
xSSFCell.SetCellErrorValue(hSSFCell.ErrorCellValue);
return;
case NPOI.SS.UserModel.CellType.String:
//xSSFCell.SetCellValue(hSSFCell.StringCellValue);
HSSFRichTextString richText = (HSSFRichTextString)hSSFCell.RichStringCellValue;
int formattingRuns = hSSFCell.RichStringCellValue.NumFormattingRuns;
XSSFRichTextString xSSFRichTextString = new XSSFRichTextString(richText.String);
for (int i = 0; i < formattingRuns; i++)
{
int startIdx = richText.GetIndexOfFormattingRun(i);
short fontIndex = richText.GetFontOfFormattingRun(i);
HSSFFont hSSFFont = hSSFCell.Sheet.Workbook.GetFontAt(fontIndex) as HSSFFont;
var xFont = FindXFont(hSSFFont, xSSFFonts, (XSSFSheet)xSSFCell.Sheet);
xSSFRichTextString.ApplyFont(startIdx, richText.Length, xFont);
}
xSSFCell.SetCellValue(xSSFRichTextString);
break;
}
if (isConvertStyle)
{
//获取需要处理的一些需要处理的样式元素信息
HSSFCellStyle hSSFCellStyle = hSSFCell.CellStyle as HSSFCellStyle;
if (hSSFCellStyle != null)
{
var xStyle = FindXStyle(hSSFCellStyle, xSSFCellStyles, (XSSFSheet)xSSFCell.Sheet);
if (xStyle != null)
{
xSSFCell.CellStyle = xStyle;
}
}
}
}
return;
} 处理样式定义 /// <summary>
/// 获取并处理单元格背景色信息
/// </summary>
/// <param name="hSSFCellStyle"></param>
/// <param name="xSSFCellStyles"></param>
/// <param name="xSSFSheet"></param>
/// <returns></returns>
private static XSSFCellStyle FindXStyle(HSSFCellStyle hSSFCellStyle, List<XSSFCellStyle> xSSFCellStyles, XSSFSheet xSSFSheet)
{
foreach (var item in xSSFCellStyles)
{
if (item.Alignment != hSSFCellStyle.Alignment)
continue;
else if (item.BorderLeft != hSSFCellStyle.BorderLeft)
continue;
else if (item.BorderRight != hSSFCellStyle.BorderRight)
continue;
else if (item.BorderTop != hSSFCellStyle.BorderTop)
continue;
else if (item.BorderBottom != hSSFCellStyle.BorderBottom)
continue;
else if (item.FillBackgroundColor != hSSFCellStyle.FillBackgroundColor)
continue;
else if (item.VerticalAlignment != hSSFCellStyle.VerticalAlignment)
continue;
else if (item.IsHidden != hSSFCellStyle.IsHidden)
continue;
else if (item.WrapText != hSSFCellStyle.WrapText)
continue;
else if (item.FillForegroundColor != hSSFCellStyle.FillForegroundColor)
continue;
else if (item.FillPattern != hSSFCellStyle.FillPattern)
continue;
else
{
return item;
}
}
var xSSFCellStyle = xSSFSheet.Workbook.CreateCellStyle() as XSSFCellStyle;
xSSFCellStyle.Alignment = hSSFCellStyle.Alignment;
xSSFCellStyle.BorderLeft = hSSFCellStyle.BorderLeft;
xSSFCellStyle.BorderRight = hSSFCellStyle.BorderRight;
xSSFCellStyle.BorderTop = hSSFCellStyle.BorderTop;
xSSFCellStyle.BorderBottom = hSSFCellStyle.BorderBottom;
xSSFCellStyle.FillBackgroundColor = hSSFCellStyle.FillBackgroundColor;
xSSFCellStyle.VerticalAlignment = hSSFCellStyle.VerticalAlignment;
xSSFCellStyle.IsHidden = hSSFCellStyle.IsHidden;
xSSFCellStyle.WrapText = hSSFCellStyle.WrapText;
xSSFCellStyle.FillForegroundColor = hSSFCellStyle.FillForegroundColor;
xSSFCellStyle.FillPattern = hSSFCellStyle.FillPattern;
xSSFCellStyles.Add(xSSFCellStyle);
return xSSFCellStyle;
} 处理字体格式信息 /// <summary>
/// 获取并处理文字格式信息
/// </summary>
/// <param name="hSSFFont"></param>
/// <param name="xSSFFonts"></param>
/// <param name="xSSFSheet"></param>
/// <returns></returns>
private static XSSFFont FindXFont(HSSFFont hSSFFont,List<XSSFFont> xSSFFonts, XSSFSheet xSSFSheet)
{
foreach (var item in xSSFFonts)
{
if (item.IsBold != hSSFFont.IsBold)
continue;
else if (item.Charset != hSSFFont.Charset)
continue;
else if (item.Color != hSSFFont.Color)
continue;
else if (item.FontHeight != hSSFFont.FontHeight)
continue;
//else if (item.FontHeightInPoints != hSSFFont.FontHeightInPoints)
// continue;
else if (item.FontName != hSSFFont.FontName)
continue;
else if (item.IsItalic != hSSFFont.IsItalic)
continue;
else if (item.IsStrikeout != hSSFFont.IsStrikeout)
continue;
else if (item.TypeOffset != hSSFFont.TypeOffset)
continue;
else if (item.Underline != hSSFFont.Underline)
continue;
else
{
return item;
}
}
var xSSFFont = xSSFSheet.Workbook.CreateFont() as XSSFFont;
xSSFFont.IsBold = hSSFFont.IsBold;
xSSFFont.Charset = hSSFFont.Charset;
xSSFFont.Color = hSSFFont.Color;
xSSFFont.FontHeight = hSSFFont.FontHeight;
//xSSFFont.FontHeightInPoints = hSSFFont.FontHeightInPoints;
xSSFFont.FontName = hSSFFont.FontName;
xSSFFont.IsItalic = hSSFFont.IsItalic;
xSSFFont.IsStrikeout = hSSFFont.IsStrikeout;
xSSFFont.TypeOffset = hSSFFont.TypeOffset;
xSSFFont.Underline = hSSFFont.Underline;
xSSFFonts.Add(xSSFFont);
return xSSFFont;
} private void ConvertXLSToXLSX(string srcFilePath, string targetFilePath){
using (var fs = new FileStream(srcFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var oldWorkbook = WorkbookFactory.Create(fs);
if(oldWorkbook is HSSFWorkbook)
{
var numberOfSheets = oldWorkbook.NumberOfSheets;
if(numberOfSheets == 1)
{
//先处理第一个sheet
var oldWorksheet = oldWorkbook.GetSheetAt(0) as HSSFSheet;
using (var fileStream = new FileStream(targetFilePath, FileMode.Create))
{
var newWorkBook = new XSSFWorkbook();
var sheet = oldWorksheet.ConvertToXSheet(newWorkBook);
newWorkBook.Add(sheet);
newWorkBook.Write(fileStream);
newWorkBook.Close();
}
oldWorkbook.Close();
}
else if(numberOfSheets > 1)
{
using (var fileStream = new FileStream(targetFilePath, FileMode.Create))
{
var newWorkBook = new XSSFWorkbook();
for (int i = 0; i < numberOfSheets; i++)
{
var oldWorksheet = oldWorkbook.GetSheetAt(i) as HSSFSheet;
var sheet = oldWorksheet.ConvertToXSheet(newWorkBook);
newWorkBook.Add(sheet);
}
newWorkBook.Write(fileStream);
newWorkBook.Close();
}
oldWorkbook.Close();
}
}
if(oldWorkbook is XSSFWorkbook)
{
if (File.Exists(targetFilePath))
{
File.Delete(targetFilePath);
}
File.Copy(srcFilePath, targetFilePath);
}
} } 该文章在 2023/12/30 0:48:26 编辑过 |
关键字查询
相关文章
正在查询... |