您的位置:首页 > 其它

记录平常工作笔记(一篇不上博客园首页的博客)(连载)

2013-04-26 22:57 423 查看

这是一篇记录平常工作笔记的博客,无论是在排版还是解说上都不会有太多要求。同时这也是一篇不上博客园首页的博客,Just记录一些工作笔记。



v读取csv文件

var allFiles = Directory.GetFiles(@"D:\TestFolder");
string dataIsNull = @"D:\dataisnull.txt";
string matchLog = @"D:\matchLog.txt";
foreach (var filePath in allFiles)
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs);
//string fileContent = sr.ReadToEnd();
//encoding = sr.CurrentEncoding;
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine = null;
string[] tableHead = null;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
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]);
dt.Columns.Add(dc);
}
}
else
{
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow();
if (aryLine.Length == columnCount)
{
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
}
dt.Rows.Add(dr);
}
}
if (aryLine != null && aryLine.Length > 0)
{
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
}
sr.Close();
fs.Close();
if (dt.Rows.Count == 0)
{
OutputLog(dataIsNull, string.Format("{0} data is null.", filePath));
continue;
}
StringBuilder mpAttributesLog = new StringBuilder();
StringBuilder allLog = new StringBuilder();
foreach (DataRow item in dt.Rows)
{
string mpAttributes = item["MPAttributes"].ToString();
var mpAttributesList = mpAttributes.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
string metaFeatures = item["MetaFeatures"].ToString().ToUpper();
string sha1 = item["Sha1"].ToString();
foreach (var mpAttributesItem in mpAttributesList)
{
if (!metaFeatures.Contains(mpAttributesItem.ToUpper().Trim()))
{
mpAttributesLog.AppendFormat("{0};", mpAttributesItem);
}
}
//allLog.AppendLine(string.Format("{0}\n{1}\n{2}\n", mpAttributesLog.ToString(), sha1, metaFeatures));
if (mpAttributesLog.Length != 0)
{
using (StreamWriter sw = File.AppendText(matchLog))
{
sw.WriteLine(mpAttributesLog.ToString());
sw.WriteLine(sha1);
sw.WriteLine(metaFeatures);
}
}
}
//if (mpAttributesLog.Length != 0)
//{
//    OutputLog(matchLog, string.Format("{0} data is null.", allLog.ToString()));
//}
}


v图片水印

/**/
/// <summary>
/// 水印位置
/// </summary>
public enum ImagePosition
{
/**/
/// <summary>
/// 左上
/// </summary>
LeftTop,
/**/
/// <summary>
/// 左下
/// </summary>
LeftBottom,
/**/
/// <summary>
/// 右上
/// </summary>
RightTop,
/**/
/// <summary>
/// 右下
/// </summary>
RigthBottom,
/**/
/// <summary>
/// 顶部居中
/// </summary>
TopMiddle,
/**/
/// <summary>
/// 底部居中
/// </summary>
BottomMiddle,
/**/
/// <summary>
/// 中心
/// </summary>
Center
}
/**/
/// <summary>
/// 图像操作类(主要用于给图片加上透明文字水印)
/// </summary>
class ImageWater_Word
{
private string _ErrMsg;
#region 出错信息
/**/
/// <summary>
/// 出错信息
/// </summary>
public string ErrMsg
{
get { return _ErrMsg; }
set { _ErrMsg = value; }
}
#endregion
#region 将文件转换成流
//public byte[] SetImageToByteArray(string fileName, ref string fileSize)
/**/
/// <summary>
/// 将文件转换成流
/// </summary>
/// <param name="fileName">文件全路径</param>
/// <returns></returns>
private byte[] SetImageToByteArray(string fileName)
{
byte[] image = null;
try
{
FileStream fs = new FileStream(fileName, FileMode.Open);
FileInfo fileInfo = new FileInfo(fileName);
//fileSize = Convert.ToDecimal(fileInfo.Length / 1024).ToString("f2") + " K";
int streamLength = (int)fs.Length;
image = new byte[streamLength];
fs.Read(image, 0, streamLength);
fs.Close();
return image;
}
catch
{
return image;
}
}
#endregion
#region 将byte转换成MemoryStream类型
/**/
/// <summary>
/// 将byte转换成MemoryStream类型
/// </summary>
/// <param name="mybyte">byte[]变量</param>
/// <returns></returns>
private MemoryStream ByteToStream(byte[] mybyte)
{
MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
return mymemorystream;
}
#endregion
#region 将byte转换成Image文件
/**/
/// <summary>
/// 将byte转换成Image文件
/// </summary>
/// <param name="mybyte">byte[]变量</param>
/// <returns></returns>
private System.Drawing.Image SetByteToImage(byte[] mybyte)
{
System.Drawing.Image image;
MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
image = System.Drawing.Image.FromStream(mymemorystream);
return image;
}
#endregion
#region 批量在图片上添加透明水印文字
/**/
/// <summary>
/// 批量在图片上添加透明水印文字
/// </summary>
/// <param name="arrsourcePicture">原来图片地址(路径+文件名)</param>
/// <param name="waterWords">需要添加到图片上的文字</param>
/// <param name="alpha">透明度(0.1~1.0之间)</param>
/// <param name="position">文字显示的位置</param>
/// <param name="fRewrite">是否覆盖原图片(如果不覆盖,那么将在同目录下生成一个文件名带0207的文件)</param>
/// <returns></returns>
public bool DrawWords(string[] arrsourcePicture, string waterWords, float alpha, ImagePosition position, bool fRewrite)
{
foreach (string imgPath in arrsourcePicture)
{
if (!DrawWord(imgPath, waterWords, alpha, position, fRewrite))
{
_ErrMsg += "——处理文件:" + imgPath + " 时出错。";
return false;
}
}
return true;
}
#endregion
#region 在图片上添加透明水印文字
/**/
/// <summary>
/// 在图片上添加透明水印文字
/// </summary>
/// <param name="sourcePicture">原来图片地址(路径+文件名)</param>
/// <param name="waterWords">需要添加到图片上的文字</param>
/// <param name="alpha">透明度(0.1~1.0之间)</param>
/// <param name="position">文字显示的位置</param>
/// <param name="fRewrite">是否覆盖原图片(如果不覆盖,那么将在同目录下生成一个文件名带0207的文件)</param>
/// <returns></returns>
public bool DrawWord(string sourcePicture, string waterWords, float alpha, ImagePosition position, bool fRewrite)
{
if (!System.IO.File.Exists(sourcePicture))
{
_ErrMsg = "文件不存在!";
return false;
}
string fileExtension = System.IO.Path.GetExtension(sourcePicture).ToLower();
if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
{
_ErrMsg = "不是图片文件!";
return false;
}
Image imgPhoto = null;
Bitmap bmPhoto = null;
Graphics grPhoto = null;
try
{
//创建一个图片对象用来装载要被添加水印的图片
imgPhoto = Image.FromStream(ByteToStream(SetImageToByteArray(sourcePicture)));
//获取图片的宽和高
int phWidth = imgPhoto.Width;
int phHeight = imgPhoto.Height;
//建立一个bitmap,和我们需要加水印的图片一样大小
bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
//SetResolution:设置此 Bitmap 的分辨率
//这里直接将我们需要添加水印的图片的分辨率赋给了bitmap
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//Graphics:封装一个 GDI+ 绘图图面。
grPhoto = Graphics.FromImage(bmPhoto);
//设置图形的品质
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
//将我们要添加水印的图片按照原始大小描绘(复制)到图形中
grPhoto.DrawImage(
imgPhoto,                                           //   要添加水印的图片
new Rectangle(0, 0, phWidth, phHeight), //  根据要添加的水印图片的宽和高
0,                                                     //  X方向从0点开始描绘
0,                                                     // Y方向
phWidth,                                            //  X方向描绘长度
phHeight,                                           //  Y方向描绘长度
GraphicsUnit.Pixel);                              // 描绘的单位,这里用的是像素
//根据图片的大小我们来确定添加上去的文字的大小
//在这里我们定义一个数组来确定
int[] sizes = new int[] { 48, 36, 28, 24, 16, 14, 12, 10 };
//字体
Font crFont = null;
//矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空
SizeF crSize = new SizeF();
//利用一个循环语句来选择我们要添加文字的型号
//直到它的长度比图片的宽度小
for (int i = 0; i < sizes.Length; i++)
{
crFont = new Font("arial", sizes[i], FontStyle.Bold);
//测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。
crSize = grPhoto.MeasureString(waterWords, crFont);
// ushort 关键字表示一种整数数据类型
if ((ushort)crSize.Width < (ushort)phWidth)
break;
}
//截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)
int yPixlesFromBottom = (int)(phHeight * .05);
//定义在图片上文字的位置
float wmHeight = crSize.Height;
float wmWidth = crSize.Width;
float xPosOfWm;
float yPosOfWm;
//设置水印的位置
switch (position)
{
case ImagePosition.BottomMiddle:
xPosOfWm = phWidth / 2;
yPosOfWm = phHeight - wmHeight - 10;
break;
case ImagePosition.Center:
xPosOfWm = phWidth / 2;
yPosOfWm = phHeight / 2;
break;
case ImagePosition.LeftBottom:
xPosOfWm = wmWidth;
yPosOfWm = phHeight - wmHeight - 10;
break;
case ImagePosition.LeftTop:
xPosOfWm = wmWidth / 2;
yPosOfWm = wmHeight / 2;
break;
case ImagePosition.RightTop:
xPosOfWm = phWidth - wmWidth - 10;
yPosOfWm = wmHeight;
break;
case ImagePosition.RigthBottom:
xPosOfWm = phWidth - wmWidth - 10;
yPosOfWm = phHeight - wmHeight - 10;
break;
case ImagePosition.TopMiddle:
xPosOfWm = phWidth / 2;
yPosOfWm = wmWidth;
break;
default:
xPosOfWm = wmWidth;
yPosOfWm = phHeight - wmHeight - 10;
break;
}
//封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。
StringFormat StrFormat = new StringFormat();
//定义需要印的文字居中对齐
StrFormat.Alignment = StringAlignment.Center;
//SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。
//这个画笔为描绘阴影的画笔,呈灰色
int m_alpha = Convert.ToInt32(255 * alpha);
SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));
//描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果
//DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。
grPhoto.DrawString(waterWords,                                    //string of text
crFont,                                         //font
semiTransBrush2,                            //Brush
new PointF(xPosOfWm + 1, yPosOfWm + 1),  //Position
StrFormat);
//从四个 ARGB 分量(alpha、红色、绿色和蓝色)值创建 Color 结构,这里设置透明度为153
//这个画笔为描绘正式文字的笔刷,呈白色
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
//第二次绘制这个图形,建立在第一次描绘的基础上
grPhoto.DrawString(waterWords,                 //string of text
crFont,                                   //font
semiTransBrush,                           //Brush
new PointF(xPosOfWm, yPosOfWm),  //Position
StrFormat);
//imgPhoto是我们建立的用来装载最终图形的Image对象
//bmPhoto是我们用来制作图形的容器,为Bitmap对象
imgPhoto = bmPhoto;
//释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满
//grPhoto.Dispose();
//将grPhoto保存
if (fRewrite)
{
imgPhoto.Save(sourcePicture);
}
else
{
// 目标图片名称及全路径
string targetImage = sourcePicture.Replace(System.IO.Path.GetExtension(sourcePicture), "") + "_0207" + fileExtension;
imgPhoto.Save(targetImage);
}
//imgPhoto.Dispose();
return true;
}
catch (Exception ex)
{
_ErrMsg = ex.Message;
return false;
}
finally
{
if (imgPhoto != null)
imgPhoto.Dispose();
if (bmPhoto != null)
bmPhoto.Dispose();
if (grPhoto != null)
grPhoto.Dispose();
}
}
#endregion
}


vappSettings读取及配置



private static string localFolder = System.Configuration.ConfigurationSettings.AppSettings["localFolder"];


vI/O

读txt

using (StreamReader streamReader = new StreamReader(@"E:\Test\local.txt"))
{
while ((lineLocal = streamReader.ReadLine()) != null)
{
lineLocal = lineLocal.Trim();
if (!string.IsNullOrEmpty(lineLocal))
{
localList.Add(lineLocal);
}
}
}


写txt

List<string> stringList = new List<string>();
//  覆盖原有的信息
using (StreamWriter sw = new StreamWriter(@"E:\SQLTest\Test.txt"))
{
foreach (string text in stringList)
{
sw.WriteLine(text);
}
}
// 不覆盖原有的信息
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(message);

}


获取文件后缀名:Path.GetExtension(file)

获取文件名 称:Path.GetFileName(file)

获取文件所有文件:Directory.GetFiles(localFolder)

获取绝对路径:Path.GetFullPath(System.Configuration.ConfigurationSettings.AppSettings["localFolder"])

v计算起始时间



vDictionary根据key得到value



vCOM组建导出EXCEL

private static System.Data.DataTable GetExcelData(string excelFilePath)
{
Excel.Application app = new Excel.Application();
Excel.Sheets sheets;
Excel.Workbook workbook = null;
object oMissiong = System.Reflection.Missing.Value;
System.Data.DataTable dt = new System.Data.DataTable();
try
{
if (app == null)
{
return null;
}

workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
sheets = workbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
if (worksheet == null)
return null;

string cellContent;
int iRowCount = worksheet.UsedRange.Rows.Count;
int iColCount = worksheet.UsedRange.Columns.Count;
Excel.Range range;
DataColumn dc;
int ColumnID = 1;
range = (Excel.Range)worksheet.Cells[1, 1];
while (range.Text.ToString().Trim() != "")
{
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = range.Text.ToString().Trim();
dt.Columns.Add(dc);

range = (Excel.Range)worksheet.Cells[1, ++ColumnID];
}

for (int iRow = 2; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();

for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Excel.Range)worksheet.Cells[iRow, iCol];

cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
dr[iCol - 1] = cellContent;
}

dt.Rows.Add(dr);
}

return dt;
}
catch
{

return null;
}
finally
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}


完美解决: Retrieving the COM class factory for component with CLSID {00024500-0000-000 (未成功)



在服务器上,

1,运行dcomcnfg打开组件服务

2,依次展开"组件服务"->"计算机"->"我的电脑"->"DCOM配置"

3,找到"Microsoft Excel应用程序"

右键打开属性对话框 点击"安全"选项卡, 把"启动和激活权限","配置权限",都选择为自定义, 然后依次点击它们的编辑,把ASPNET添加进去,并加入所有的权限..

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: